<?php

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use JMessage\JMessage;
use JMessage\IM\User;
use JMessage\IM\ChatRoom;

require_once IA_ROOT . '/addons/goouc_class/inc/phonecode/sendSms.php';
require_once IA_ROOT . '/addons/goouc_class/inc/common/WxPayJsApiPay.php';
require_once IA_ROOT . "/addons/goouc_class/inc/common/AliyunVod.php";
require_once IA_ROOT . '/addons/goouc_class/inc/common/wxBizDataCrypt.php';
require_once IA_ROOT . '/addons/goouc_class/inc/common/wxpay/log.php';
require_once IA_ROOT . '/addons/goouc_class/inc/common/wxpay/WxPayConfig.php';
require_once IA_ROOT . '/addons/goouc_class/inc/common/wxpay/lib/WxPayData.php';
require_once IA_ROOT . '/addons/goouc_class/inc/common/wxpay/lib/WxPayApi.php';
require_once IA_ROOT . '/addons/goouc_class/inc/qiniu/autoload.php';
require_once IA_ROOT . '/web/common/tpl.func.php';
require_once IA_ROOT . '/addons/goouc_class/library/JMessage/autoload.php';
defined('IN_IA') or exit('Access Denied');

class goouc_classModuleWxapp extends WeModuleWxapp
{
    //返回状态值  后台报错 1开头  其他2开头 前台数据传输错误 3开头
    public $t_cardinfo = 'goouc_class_cardinfo';
    public $t_banner = 'goouc_class_banner';
    public $t_lesson = 'goouc_class_lesson';
    public $t_son = 'goouc_class_son';
    public $t_city = 'goouc_class_city';
    public $t_teacher = 'goouc_class_teacher';
    public $t_subject = 'goouc_class_subject';
    public $t_class = 'goouc_class_class';
    public $t_classtype = 'goouc_class_classtype';
    public $t_semester = 'goouc_class_semester';
    public $t_voidtype = 'goouc_class_voidtype';
    public $t_level = 'goouc_class_level';
    public $t_shartitle = 'goouc_class_shartitle';
    public $t_poster = 'goouc_class_poster_new';
    public $t_user = 'goouc_class_user';
    public $t_signin = 'goouc_class_signin';
    public $t_signup = 'goouc_class_user_signup';
    public $t_phonecode = 'goouc_class_phonecode';
    public $t_userlooktime = 'goouc_class_userlook';
    public $t_userlooktimes = 'goouc_class_userlookm';
    public $t_user_exchange = 'goouc_class_user_exchange';
    public $t_user_group = 'goouc_class_user_group';
    public $t_user_group_info = 'goouc_class_user_group_info';
    public $t_order = 'goouc_class_order';
    public $t_user_study_speed = 'goouc_class_user_study_speed';
    public $t_live_message = 'goouc_class_live_message';
    public $t_user_study_now = 'goouc_class_user_study_sign';
    public $t_category = 'goouc_class_category';
    public $t_article = 'goouc_class_article';
    public $t_practice = 'goouc_class_practice';
    public $qiniu_url = 'http://classimage.goouc.com/';
    // public $qiniu_url = 'https://s.ixiaohe.com/attachment/';
    /** 3.0接口* */
    //登录接口
    public function doPageLogin()
    {
        global $_W, $_GPC;
        $code = trim($_GPC['code']);
        //获取unionid
        $iv = $_GPC['iv'];
        $encryptedData = $_GPC['encryptedData'];
        $appid = $_W['account']['key'];
        if (!empty($code) && !empty($iv) && !empty($encryptedData)) {
            $info = json_decode($this->getopenidnew($code), true);
            $session_key = $info['session_key'];
            $pc = new WXBizDataCrypt($appid, $session_key);
            $pc->decryptData($encryptedData, $iv, $dat);
            $info = json_decode($dat, true);
            if (empty($info)) {
                return $this->result(1, '解密获取用户信息失败', ['code' => 1001, 'msg' => '解密获取用户信息失败']);
            }
            $userinfo = pdo_fetch("SELECT `id`,`status`,`unionId` FROM " . tablename($this->t_user) . " WHERE openid = :openid AND weid = :weid", array(':openid' => $info['openId'], ':weid' => $_W['uniacid']));
            //先产寻openid是否存在  不存在的话 再查一下unionId对应的用户是否存在
            if (empty($userinfo)) {
                $userinfo = pdo_fetch("SELECT `id`,`status`,`unionId` FROM " . tablename($this->t_user) . " WHERE unionId = :unionId AND weid = :weid", array(':unionId' => $info['unionId'], ':weid' => $_W['uniacid']));
            }
            //先产寻openid是否存在  不存在的话 再查一下unionId对应的用户是否存在
            if (empty($userinfo)) {
                $data = array();
                $data['openid'] = $info['openId'];
                $data['nickname'] = json_encode($info['nickName']);
                $data['headimg'] = $info['avatarUrl'];
                $data['weid'] = $_W['uniacid'];
                $data['unionId'] = empty($info['unionId']) ? '' : $info['unionId'];
                $data['createtime'] = time();
                if (empty($data['nickname']) || empty($data['openid'])) {
                    return $this->result(1, '用户注册失败', ['code' => 1003, 'msg' => '用户注册失败']);
                }
                $res = pdo_insert($this->t_user, $data);
                if ($res) {
                    $userid = pdo_insertid();
                    return $this->result(0, '注册并登录成功', array('uid' => $userid));
                } else {
                    return $this->result(1, '用户注册失败', ['code' => 1003, 'msg' => '用户注册失败']);
                }
            } else {
                if ($userinfo['status'] == 0) {
                    return $this->result(1, '您已被禁用，暂时无法登陆小程序', ['code' => 2001, 'msg' => '您已被禁用，暂时无法登陆小程序']);
                }
                //上线前开启
                if (empty($userinfo['unionId'])) {
                    $data = array();
                    $data['nickname'] = json_encode($info['nickName']);
                    $data['headimg'] = $info['avatarUrl'];
                    $data['unionId'] = $info['unionId'];
                    $data['new_status'] = 0;
                    pdo_update('goouc_class_user', $data, array('id' => $userinfo['id']));
                }
                //分享新生成的用户  没有昵称和头像  更新一下头像和昵称
                if (empty($userinfo['niackname'])) {
                    $data = array();
                    $data['nickname'] = json_encode($info['nickName']);
                    $data['headimg'] = $info['avatarUrl'];
                    pdo_update('goouc_class_user', $data, ['id' => $userinfo['id']]);
                }
                if (empty($userinfo['openid'])) {
                    //将用户openid填入
                    $data = array();
                    $data['nickname'] = json_encode($info['nickName']);
                    $data['headimg'] = $info['avatarUrl'];
                    $data['openid'] = $info['openId'];
                    pdo_update('goouc_class_user', $data, ['id' => $userinfo['id']]);
                }
                return $this->result(0, '老用户登录更新用户信息成功', array('uid' => $userinfo['id']));
            }
        } else {
            return $this->result(1, '未获取到code等参数值', ['code' => 1002, 'msg' => '未获取到code等参数值']);
        }
    }

    //处理老用无unionId的问题
    public function doPageRefresh()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $code = trim($_GPC['code']);
        $iv = $_GPC['iv'];
        $encryptedData = $_GPC['encryptedData'];
        $appid = $_W['account']['key'];
        if (!empty($code) && !empty($iv) && !empty($encryptedData)) {
            $info = json_decode($this->getopenidnew($code), true);
            $session_key = $info['session_key'];
            $pc = new WXBizDataCrypt($appid, $session_key);
            $pc->decryptData($encryptedData, $iv, $dat);
            $info = json_decode($dat, true);
            $data['unionId'] = $info['unionId'];
            pdo_update('goouc_class_user', $data, array('id' => $uid));
        }
    }

    //返回用户信息接口  原名称 userinfo
    public function doPageUserinfonew()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        $config = $this->module['config'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户id', ['code' => 3001, 'msg' => '未获取到用户id']);
        }
        $userinfo = pdo_get($this->t_user, array('id' => $uid, 'weid' => $_W['uniacid']), array('id', 'nickname', 'name', 'phone', 'headimg', 'myheaderimg', 'card', 'sex', 'city1', 'city2', 'school', 'classid', 'status', 'unionId', 'type', 'teacherid'));
        if (empty($userinfo['unionId'])) {
            $have_unionid = 2;
        } else {
            $have_unionid = 1;
        }
        if (!empty($userinfo['myheaderimg'])) {
            $userinfo['headimg'] = $userinfo['myheaderimg'];
        }
        if (empty($userinfo['name'])) {
            $userinfo['name'] = json_decode($userinfo['nickname']);
        }
        $userinfo['nickname'] = json_decode($userinfo['nickname']);
        if (empty($userinfo)) {
            return $this->result(1, '获取用户数据失败', ['code' => 1001, 'msg' => '获取用户数据失败']);
        } elseif ($userinfo['status'] == 0) {
            return $this->result(1, '您已被禁用，暂时无法登陆小程序', ['code' => 2001, 'msg' => '您已被禁用，暂时无法登陆小程序']);
        }
        $config = $this->module['config'];
        $sharset = array('nstatus' => $config['nstatus'], 'nnum' => $config['nnum'], 'lstatus' => $config['lstatus'], 'lnum' => $config['lnum'], 'sstatus' => $config['sstatus'], 'snumber' => $config['snumber'], 'snum' => $config['snum'], 'pay_status' => $config['pay_status']);
        $sharetitle = pdo_get('goouc_class_shartitle', array('weid' => $_W['uniacid']));
        //上面有问题
        $userinfo['cardnum'] = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_exchange) . " ue JOIN " . tablename($this->t_cardinfo) . " c ON ue.cid = c.id where ue.weid = :weid AND ue.uid = :uid AND ue.year = :year  order by addtime DESC", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':year' => date('Y', time())));
        $has_underline = 0;
        if (!empty($userinfo['phone'])) {
            $has_underline = pdo_getcolumn('goouc_class_lesson_underline_student', array('weid' => $_W['uniacid'], 'phone' => trim($userinfo['phone']), 'lesson_id >' => 0), 'COUNT(id)');
            if (!empty($has_underline)) {
                $has_underline = 1;
            }
        }
        $userinfo['has_underline'] = intval($has_underline);//practice_remind
        $userinfo['templateid'] = [$config['templateid'], $config['ntemplateid']];//订阅消息模板ntemplateid
        $userinfo['practicestatus'] = $config['practice_status'];//习题开关
        $userinfo['practice_remind'] = $config['practice_remind'];//订阅消息开关
        return $this->result(0, '用户详情', array('userinfo' => $userinfo, 'sharset' => $sharset, 'sharetitle' => $sharetitle, 'about' => $config['about'], 'have_unionid' => $have_unionid));
    }

    //咨询
    public function doPageAbout()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        return $this->result(0, '咨询', ['about' => $config['about']]);
    }

    //首页数据 原接口名index
    public function doPageIndexnew()
    {
        global $_W, $_GPC;
        $contion = "weid = :weid AND status = 1";
        $params[':weid'] = $_W['uniacid'];
        $op = empty($_GPC['op']) ? 'city' : $_GPC['op'];
        if ($op == 'city') {
            $city = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename($this->t_city) . " WHERE " . $contion, $params);
            if (empty($city)) {
                $city = pdo_getall($this->t_city, array('weid' => $_W['uniacid']));
            }
            if (count($city) == 1) {
                $citystatus = 1;
            } elseif (count($city) > 1) {
                $city = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename($this->t_city) . " WHERE " . $contion, $params);
                $citystatus = 2;
            }
            return $this->result(0, '城市信息', array('city' => $city, 'status' => $citystatus));
        } elseif ($op == 'class') {
            $class = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename($this->t_class) . " WHERE " . $contion, $params);
            return $this->result(0, '年级列表', array('class' => $class));
        } elseif ($op == 'subject') {
            $classid = $_GPC['classid'];
            if (!empty($classid)) {
                $contion .= " AND id = :id";
                $params[':id'] = $classid;
                $classlist = pdo_fetch("SELECT `id`,`name`,`subjectid` FROM " . tablename($this->t_class) . " WHERE " . $contion, $params);
                $arr_subject = unserialize($classlist['subjectid']);
                foreach ($arr_subject as $su => $us) {
                    $subject[] = pdo_fetch("SELECT `id`,`name` FROM " . tablename("goouc_class_subject") . " WHERE id = :id", array(':id' => $us));
                }
            } else {
                $subject = pdo_getall($this->t_subject, array('weid' => $_W['uniacid'], 'status' => 1));
            }
            return $this->result(0, '学科列表', array('subject' => $subject));
        } elseif ($op == 'semester') {
            $semester = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename($this->t_semester) . " WHERE " . $contion, $params);
            return $this->result(0, '学期列表', array('semester' => $semester));
        } elseif ($op == 'voidtype') {
            $voidtype = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename($this->t_voidtype) . " WHERE " . $contion, $params);
            return $this->result(0, '类型列表', array('voidtype' => $voidtype));
        } elseif ($op == 'year') {
            $year = array(
                '0' => array(
                    'id' => 2019,
                    'name' => 2019,
                ),
                '1' => array(
                    'id' => 2020,
                    'name' => 2020,
                )
            );
            return $this->result(0, '年份列表', array('year' => $year));
        } elseif ($op == 'lesson') {

            $contion = " l.weid = :weid AND l.status = 1";
            $cityid = $_GPC['cityid'];
            $classid = $_GPC['classid'];
            $classtypeid = $_GPC['classtypeid'];
            $subjectid = $_GPC['subjectid'];
            $semesterid = $_GPC['semesterid'];
            $voidtypeid = $_GPC['voidtypeid'];
            $yearid = $_GPC['yearid'];
            $priceid = $_GPC['priceid'];
            //用户id  判断用户是否报名课程
            $uid = $_GPC['uid'];
            if (!empty($cityid)) {
                $contion .= " AND l.cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($classid)) {
                $contion .= " AND l.classid LIKE '%\"" . $classid . "\"%'";
            }
            if (!empty($subjectid)) {
                $contion .= " AND l.subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            if (!empty($semesterid)) {
                $contion .= " AND l.semesterid = :semesterid";
                $params[':semesterid'] = $semesterid;
            }
            if (!empty($voidtypeid)) {
                $contion .= " AND l.voidtypeid = :voidtypeid";
                $params[':voidtypeid'] = $voidtypeid;
            }
            if (!empty($yearid)) {
                $contion .= " AND l.yearid = :yearid";
                $params[':yearid'] = $yearid;
            }
            if (!empty($priceid)) {
                if ($priceid == 2) {
                    //免费课程
                    $contion .= ' AND (l.paytype = :paytype1 OR l.paytype = :paytype2 )';
                    $params[':paytype1'] = 2;
                    $params[':paytype2'] = 3;
                } else {
                    $contion .= ' AND l.paytype = :paytype ';
                    $params[':paytype'] = 4;
                }
            }
            if (!empty($classtypeid)) {
                $contion .= ' AND l.classtypeid = :classtypeid';
                $params[':classtypeid'] = $classtypeid;
            }
            //搜索框搜索
            $keywords = $_GPC['keywords'];
            if (!empty($keywords)) {
                $contion .= " AND (l.title like '%" . $keywords . "%' OR t.name like '%" . $keywords . "%' )";
            }
            //判断是否筛选了 如果筛选了 要查出来所有的课程 并且要做分页
            if (empty($classid) && empty($subjectid) && empty($semesterid) && empty($voidtypeid) && empty($yearid) && empty($priceid) && empty($classtypeid) && empty($keywords)) {
                //筛选页面的数据
                $pindex = empty($_GPC['page']) ? 1 : $_GPC['page'];
                $psize = 4;
                if ($_W['uniacid'] == 20) {
                    $contion .= " AND l.is_underline = 0";
                }
                $contion .= '  AND  l.voidtypeid != 0 AND l.teacherid != 0 AND l.subjectid != 0 AND l.cityid != 0';
                $lesson = pdo_fetchall("SELECT l.id,`title`,`image`,`paytype`,`xhbnumber`,`pay_money`,`old_money`,`is_only`,`is_groupbuy`,`fic_study_num`,`study_num`,`pay_num` FROM " . tablename($this->t_lesson) . " l JOIN " . tablename($this->t_teacher) . " t ON l.teacherid = t.id WHERE " . $contion . " and recommend  = 1 ORDER BY l.order DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, $params);
                $total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_lesson) . " l JOIN " . tablename($this->t_teacher) . " t ON l.teacherid = t.id  where " . $contion, $params);
                $pages = ceil($total / $psize);
//                if (empty($lesson)) {
//                    $contionl = 'weid = :weid AND status = 1 AND voidtypeid != 0 AND teacherid != 0 AND subjectid != 0 AND cityid != 0 AND recommend !=0';
//                    if ($_W['uniacid'] == 20) {
//                        $contionl .= " AND is_underline = 0";
//                    }
//                    $lesson = pdo_fetchall("SELECT `id`,`title`,`image`,`paytype`,`xhbnumber`,`pay_money`,`old_money`,`is_only`,`is_groupbuy` FROM " . tablename($this->t_lesson) . " WHERE " . $contionl . " ORDER BY `order` DESC LIMIT 0,4 ", $params);
//                }
                // $pages = 1;
                $isselected = 2;
            } else {
                //筛选页面的数据
                $pindex = empty($_GPC['page']) ? 1 : $_GPC['page'];
                $psize = 8;
                $contion .= '  AND  l.voidtypeid != 0 AND l.teacherid != 0 AND l.subjectid != 0 AND l.cityid != 0';
                if ($_W['uniacid'] == 20) {
                    $contion .= " AND l.is_underline = 0";
                }
                $lesson = pdo_fetchall("SELECT l.id,`title`,`image`,`paytype`,`xhbnumber`,`pay_money`,`old_money`,`is_only`,`is_groupbuy`,`fic_study_num`,`study_num`,`pay_num` FROM " . tablename($this->t_lesson) . " l JOIN " . tablename($this->t_teacher) . " t ON l.teacherid = t.id WHERE " . $contion . " ORDER BY l.order DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, $params);
                $total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_lesson) . " l JOIN " . tablename($this->t_teacher) . " t ON l.teacherid = t.id  where " . $contion, $params);
                $pages = ceil($total / $psize);
                $isselected = 1;
            }
            //处理课程数据
            foreach ($lesson as $k => $v) {
                // $lesson[$k]['image'] = $_W['attachurl'].$v['image'];
                if ($_W['uniacid'] == 20) {
                    $lesson[$k]['image'] = $this->qiniu_url . $v['image'];
                } else {
                    $lesson[$k]['image'] = $_W['attachurl'] . $v['image'];
                }
                //已报名人数
                $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $v['id']));
                $lesson[$k]['studynum'] = $v['fic_study_num'] + $signupnum;
                //判断用户是否报名
                if (empty($uid)) {
                    $lesson[$k]['signup'] = 2;
                } else {
                    //查询数据库是否报名
                    $signup = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_signup) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid", array(':weid' => $_W['uniacid'], ':uid' => $uid, 'lessonid' => $v['id']));
                    $phone = pdo_get('goouc_class_user', array('id' => $uid, 'weid' => $_W['uniacid']), array('phone'));
                    $underlinesignup = pdo_get('goouc_class_lesson_underline_student', array('phone' => $phone['phone'], 'weid' => $_W['uniacid'], 'lesson_id' => $v['id']), array('id'));
                    if ($signup || $underlinesignup['id']) {
                        $lesson[$k]['signup'] = 1;
                    } else {
                        $lesson[$k]['signup'] = 2;
                    }
                }
            }
            //退费逻辑 现在这里
            //查询所有失败的团
            //            $config = $this->module['config'];
//            if($config['refund_status'] == 1){
//                $faile_grouplist = pdo_fetchall("select * from ".tablename($this->t_user_group)." where refund_status = 2 AND ( (createtime < :endtime and groupnum < :groupnum) || status = 3 )",[':endtime'=>time()-($config['validtime'] * 3600),':groupnum'=>$config['groupnum']]);
//                foreach($faile_grouplist as $k=>$v){
//                    $faile_user_list = pdo_fetchall("select * from ".tablename($this->t_user_group_info)." where groupid = :groupid and refund_status = :refund_status",[':groupid'=>$v['id'],':refund_status'=>2]);
//                    foreach($faile_user_list as $kk=>$vv){
            // $this->refund($vv['uid'],$vv['id']);
//                    }
//                }
//            }
            return $this->result(0, '数据列表', array('lesson' => $lesson, 'pages' => $pages, 'isselected' => $isselected, 'contion' => $contion, 'params' => $params));
        } elseif ($op == 'classtype') {
            $classtype = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename($this->t_classtype) . " WHERE " . $contion, $params);
            return $this->result(0, '班型列表', array('classtype' => $classtype));
        } elseif ($op == 'price') {
            $arr = array(
                ['id' => 2, 'name' => '免费'],
                ['id' => 3, 'name' => '付费']
            );
            return $this->result(0, '收费分类', array('price' => $arr));
        }
    }

    //完善信息
    public function doPageEdituserinfo()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户uid', ['code' => 3001, 'msg' => '未获取到用户uid']);
        }
        $config = $this->module['config'];
        $op = empty($_GPC['op']) ? 'info' : $_GPC['op'];
        $userinfo = pdo_get($this->t_user, array('id' => $uid));
        if (empty($userinfo) || $userinfo['status'] == 0) {
            return $this->result(1, '用户不存在或被禁用', ['code' => 2001, 'msg' => '用户不存在被禁用']);
        }
        if ($op == 'info') {
            $data['name'] = $userinfo['name'];
            $data['headimg'] = !empty($userinfo['myheaderimg']) ? $userinfo['myheaderimg'] : $userinfo['headimg'];
            $data['sex'] = $userinfo['sex'];
            $data['classid'] = $userinfo['classid'];
            $data['school'] = $userinfo['school'];
            $data['city1'] = $userinfo['city1'];
            $data['city2'] = $userinfo['city2'];
            $data['phone'] = $userinfo['phone'];
            $classlist = pdo_fetchall("select id,name from " . tablename($this->t_class) . " where weid = :weid and status = :status ORDER BY `order` DESC ", array(':weid' => $_W['uniacid'], ':status' => 1));
            /*$classidlist = array_column($classlist,'id');
            if(!in_array($userinfo['classid'],$classidlist)){
                $data['classid'] = 0;
                $data['explain'] = '您所选的年级不存在，请重新选择';
            }*/
            return $this->result(0, '返回用户信息', ['userinfo' => $data, 'classlist' => $classlist]);
        } elseif ($op == 'edit') {
            $dat = json_decode(htmlspecialchars_decode($_GPC['userinfo']), true);
            //return $this->result(0,'看一下',$dat);
            $data['name'] = $dat['name'];
            $data['sex'] = $dat['sex'];
            $data['classid'] = $dat['classid'];
            $data['school'] = $dat['school'];
            $data['city1'] = $dat['city1'];
            $data['city2'] = $dat['city2'];
            $data['phone'] = $dat['phone'];
            $data['myheaderimg'] = $dat['headimg'];
            //查下教师表有没有这个手机号
            $teacherid = pdo_fetchcolumn('select id from ' . tablename('goouc_class_teacher') . ' where weid = :weid AND mobile = :phone', array(':weid' => $_W['uniacid'], ':phone' => $dat['phone']));
            if (!empty($teacherid)) {
                $data['type'] = 2;
                $data['teacherid'] = $teacherid;
                $type = 2;
            }
            //判断是否修改手机号了 如果修改手机号了  验证一下手机号是否重复
            if ($_GPC['ischangephone'] == 1) {
                //判断手机号是否已经存在
                //$has = pdo_get($this->t_user,array('phone'=>$data['phone']));
                $has = pdo_getcolumn($this->t_user, array('weid' => $_W['uniacid'], 'phone' => $data['phone']), 'id');
                if (!empty($has) && ($has != $uid)) {
                    return $this->result(1, '该手机号已经绑定', ['code' => 3002, 'msg' => '该手机号已经绑定']);
                }
            }
            //判断前台传过来的数据
            if (empty($data['name']) || empty($data['school']) || empty($data['classid'])) {
                return $this->result(1, '修改数据不能为空');
            }
            $res = pdo_update($this->t_user, $data, array('id' => $uid));
            //修改头像以及完善信息 发放兑换币
            if (!empty($data['myheaderimg']) && empty($userinfo['myheaderimg'])) {
                pdo_query("update " . tablename($this->t_user) . " set card = card + " . $config['setheaderimg'] . " where id = :id", array(':id' => $uid));
            }
            if (!empty($data['phone']) && empty($userinfo['phone'])) {
                pdo_query("update " . tablename($this->t_user) . " set card = card + " . $config['setuserinfo'] . " where id = :id", array(':id' => $uid));
            }
            return $this->result(0, '保存成功', ['code' => 200, 'msg' => '信息保存成功']);
            // if($res){
            // }else{
            //     return $this->result(1,'保存成功',['code'=>1001,'msg'=>'信息保存失败']);
            // }
        }
    }

    //首页轮播图 原名称banner
    public function doPageBannernew()
    {
        global $_W, $_GPC;
        $classid = $_GPC['classid'];
        $banner = pdo_fetchall("select * from " . tablename($this->t_banner) . " where weid = :weid and status = :status and position = :position and classid like '%\"" . $classid . "\"%' ", array(':weid' => $_W['uniacid'], ':status' => 1, ':position' => 1));
        //$banner = pdo_getall('goouc_class_banner',array('weid'=>$_W['uniacid'],'status'=>1,'position'=>1,'classid'=>$classid));
        if (empty($banner)) {
            $banner = pdo_getall('goouc_class_banner', array('weid' => $_W['uniacid'], 'status' => 1, 'position' => 1));
        }
        foreach ($banner as $k => $v) {
            $banner[$k]['image'] = $_W['attachurl'] . $v['image'];
        }
        return $this->result(0, '首页轮播图', array('banner' => $banner));
    }

    //上传头像接口 原名称  uploadimage
    public function doPageUploadimagenew()
    {
        global $_GPC, $_W;
        $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');
        $max_file_size = 2000000;
        $weid = $_W['uniacid'];
        $destination_folder = $_GPC['m'] . "/" . $weid . '/' . date('Y', time()) . '/';
        if (!is_uploaded_file($_FILES["upfile"]['tmp_name'])) {
            return $this->result(0, '图片不存在!');
        }
        $file = $_FILES["upfile"];
        if ($max_file_size < $file["size"]) {
            return $this->result(0, '文件太大!');
        }
        if (!in_array($file["type"], $uptypes)) {
            return $this->result(0, '文件类型不符!' . $file["type"]);
        }
        if (!file_exists("../attachment/" . $destination_folder)) {
            mkdir("../attachment/" . $destination_folder, 0777, true);
        }
        $filename = $file["tmp_name"];
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo['extension'];
        $imgpath = $destination_folder . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;
        $destination = "../attachment/" . $imgpath;
        if (!move_uploaded_file($filename, $destination)) {
            return $this->result(0, '移动文件出错');
        }
        $pinfo = pathinfo($destination);
        $fname = $pinfo['basename'];
        //获取七牛配置
        //$qiniuConfig = getQiNiu();
        $setting = pdo_get('uni_settings', array('uniacid' => $weid), array('remote'));
        $config = unserialize($setting['remote']);
        $qiniuConfig = $config['qiniu'];
        if ($config['type'] == 3) {
            //上传七牛
            $accessKey = $qiniuConfig['accesskey'];
            $secretKey = $qiniuConfig['secretkey'];
            $uploadMgr = new UploadManager();
            $auth = new Auth($accessKey, $secretKey);
            // 构建 UploadManager 对象
            $bucket = $qiniuConfig['bucket'];
            // 生成上传Token
            $token = $auth->uploadToken($bucket);
            $filePath = IA_ROOT . '/attachment/' . $imgpath;
            list($ret, $err) = $uploadMgr->putFile($token, $imgpath, $filePath);
            if ($err !== null) {
                return $this->result(0, '上传失败');
            }
            //删除本地图片
            unlink(ATTACHMENT_ROOT . $destination_folder . $fname);
            echo $qiniuConfig['url'] . '/' . $destination_folder . $fname;
            exit;
        } else {
            echo $_W['attachurl'] . $destination_folder . $fname;
            exit;
        }
    }

    //七牛云图片
    function getImgUrl($img)
    {
        global $_W;
        //获取七牛配置
        $setting = pdo_get('uni_settings', array('uniacid' => $_W['uniacid']), array('remote'));
        $config = unserialize($setting['remote']);
        $qiniuConfig = $config['qiniu'];
        if ($config['type'] == 3) {
            $url = $qiniuConfig['url'];
            $imgurl = $url . '/' . $img;
        } else {
            $imgurl = $_W['siteroot'] . 'attachment/' . $img;
        }
        return $imgurl;
    }

    //发送手机验证码
    public function doPageSendcode()
    {
        global $_W, $_GPC;
        $phone = $_GPC['phone'];
        if (empty($phone) || !preg_match('/^[1][3,4,5,7,8,9][0-9]{9}$/', $phone)) {
            return $this->result(1, '未获取到要发送验证码的手机号', ['code' => 3002, 'msg' => '未获取到要发送验证码的手机号']);
        }
        $config = $this->module['config'];
        $phoneset = array('accessKeyId' => $config['accessKeyId'], 'accessKeySecret' => $config['accessKeySecret'], 'SignName' => $config['SignName'], 'TemplateCode' => $config['TemplateCode']);
        $obj = new send();
        $code = random(4, true);
        $res = $obj->sendcode($phone, $code, $phoneset);
        $res = json_decode(json_encode($res), true);
        if ($res['Code'] == 'OK') {
            $data['phone'] = $phone;
            $data['code'] = $code;
            $data['createtime'] = time();
            $data['weid'] = $_W['uniacid'];
            $res = pdo_insert($this->t_phonecode, $data);
            if ($res) {
                return $this->result(0, '发送验证码成功', 1);
            } else {
                return $this->result(1, '保存验证码失败', ['code' => 1001, 'msg' => '保存验证码失败']);
            }
        } elseif ($res['Code'] == "isv.BUSINESS_LIMIT_CONTROL") {
            return $this->result(1, '发送过于频繁', ['code' => 3001, 'msg' => '发送过于频繁']);
        }
    }

    //验证手机验证码
    public function doPageCheckcode()
    {
        global $_W, $_GPC;
        $phone = $_GPC['phone'];
        $code = $_GPC['code'];
        if (empty($phone) || empty($code)) {
            return $this->result(1, '未获取到手机号或用户所填验证码', ['code' => 3003, 'msg' => '未获取到手机号或用户所填验证码']);
        }
        $info = pdo_fetch("SELECT `code`,`createtime` FROM " . tablename($this->t_phonecode) . " WHERE phone = :phone AND weid = :weid ORDER BY `createtime` DESC ", array(':phone' => $phone, ':weid' => $_W['uniacid']));
        if ($code != $info['code']) {
            return $this->result(1, '验证码错误', ['code' => 3001, 'msg' => '验证码错误']);
        } else {
            $time = time() - $info['createtime'];
            if ($time > 300) {
                return $this->result(1, '验证码过期', ['code' => 3002, 'msg' => '验证码过期']);
            } else {
                return $this->result(0, '验证码正确', 1);
            }
        }
    }

    //进入签到页面数据
    public function doPageSigninnew()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户ID');
        }
        //查询用户当月是否签到
        $config = $this->module['config'];
        $is_signin = pdo_get($this->t_signin, array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01', time())));
        if (empty($is_signin)) {
            $data['signinstatus'] = 1;
            $data['day'] = array();
            $data['signinnum'] = 0;
            $data['csign'] = 2;
        } else {
            if ($is_signin['date'] != date('Ymd', time())) {
                //当天还未签到
                $data['signinstatus'] = 1;
            } else {
                $data['signinstatus'] = 2;
            }
            //判断是否达到连续签到的需求
            $lday = $config['lday'];
            //$ldnum = $config['ldnum'];
            if ($is_signin['num'] > $lday && $is_signin['status'] == 0) {
                $data['csign'] = 1;//可领取连续签到奖励
            } else {
                $data['csign'] = 2;//不可领取连续签到奖励
            }
            //当月签到情况
            $data['day'] = unserialize($is_signin['day']);
            //签到月份
            $data['month'] = date('Y-m', time());
            //连续签到天数
            $data['signinnum'] = $is_signin['num'];
        }
        $data['lnum'] = $config['lnum'];//每天签到获得奖励数
        $data['lday'] = $config['lday'];//连续签到多少天
        $data['ldnum'] = $config['ldnum'];//连续签到给多少兑换币
        $data['lstatus'] = $config['lstatus'];//是否开启签到获得兑换币
        $data['lrole'] = explode(';', $config['lrole']);//签到规则
        return $this->result(0, '签到页面数据', $data);
    }

    //处理签到
    public function doPageDosignin()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $sharset = array('nstatus' => $config['nstatus'], 'nnum' => $config['nnum'], 'lstatus' => $config['lstatus'], 'lnum' => $config['lnum'], 'sstatus' => $config['sstatus'], 'snumber' => $config['snumber'], 'snum' => $config['snum'], 'zsnum' => $config['zsnum']);
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户id', ['code' => 3001, 'msg' => '未获取到用户id']);
        }
        $logininfo = pdo_get($this->t_signin, array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01', time())));
        $data['uid'] = $uid;
        $data['weid'] = $_W['uniacid'];
        if (empty($logininfo)) {
            //该用户还没有签到过  生成一条签到记录数据
            $data['num'] = 1;
            //最近一次签到的日期
            $data['date'] = date('Ymd', time());
            $data['month'] = date('Ym01', time());
            $a = array(date('d', time()));
            $data['day'] = serialize($a);
            //生成一条记录并返回签到成功
            $res = pdo_insert($this->t_signin, $data);
            if ($res) {
                // 发相应的兑换币
                if ($sharset['lstatus'] == 1) {
                    // 查询是否达到签到连续天数
                    $signinfo = pdo_get($this->t_signin, array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01')));
                    if ($signinfo['num'] >= $config['lday'] && $signinfo['status'] == 0) {
                        //领取连续签到奖励
                        $sharset['lnum'] = $sharset['lnum'] + $sharset['ldnum'];
                    }
                    pdo_query("UPDATE " . tablename($this->t_user) . " set card = card + " . $sharset['lnum'] . "  where id=:id", array(":id" => $uid));
                }
                return $this->result(0, '当天签到成功', array('status' => 1, 'num' => $sharset['lnum']));
            } else {
                return $this->result(1, '当天签到失败', ['code' => 3001, 'msg' => '当天签到失败']);
            }
        } elseif ($logininfo['date'] == date('Ymd', time())) {
            return $this->result(1, '今日已签到成功明天再来', ['code' => 3002, 'msg' => '今日已签到成功明天再来']);
        } else {
            $data['date'] = date('Ymd', time());
            $data['month'] = date('Ym01', time());
            if ($data['date'] - $logininfo['date'] == 1) {
                $data['num'] = $logininfo['num'] + 1;
            } else {
                $data['num'] = 1;
            }
            $a = unserialize($logininfo['day']);
            $a[] = date('d', time());
            $data['day'] = serialize($a);
            $res = pdo_update('goouc_class_signin', $data, array('uid' => $uid, 'weid' => $_W['uniacid']));
            if ($res) {
                // 发相应的听课券
                if ($sharset['lstatus'] == 1) {
                    // 查询是否达到签到连续天数
                    $signinfo = pdo_get('goouc_class_signin', array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01')));
                    if ($signinfo['num'] >= $config['lday'] && $signinfo['status'] == 0) {
                        //领取连续签到奖励
                        $sharset['lnum'] = $sharset['lnum'] + $sharset['ldnum'];
                    }
                    pdo_query("UPDATE " . tablename('goouc_class_user') . " set card = card + " . $sharset['lnum'] . "  where id=:id", array(":id" => $uid));
                }
                return $this->result(0, '当天签到成功', array('status' => 1, 'num' => $sharset['lnum']));
            } else {
                return $this->result(1, '当天签到失败', ['code' => 3001, 'msg' => '当天签到失败']);
            }
        }
    }

    //排行榜 原名称ranking
    public function doPageRankingnew()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $tell = $config['number'];
        $userid = intval($_GPC['uid']);
        if (empty($userid)) {
            return $this->result(1, '未获取到用户id', ['code' => 3001, 'msg' => '未获取到用户']);
        }
        //返回当前用户的信息  缺少用户的排名
        $userinfo = pdo_fetch("SELECT `id`,`name`,`headimg`,`myheaderimg`,`nickname` FROM " . tablename($this->t_user) . " WHERE id = :id AND weid = :weid", array(':id' => $userid, ':weid' => $_W['uniacid']));
        if (!empty($userinfo['myheaderimg'])) {
            $userinfo['headerimg'] = $_W['attachment'] . $userinfo['myheaderimg'];
        } else {
            $userinfo['headerimg'] = $userinfo['headimg'];
        }
        unset($userinfo['headimg']);
        unset($userinfo['myheaderimg']);
        $userinfo['nickname'] = json_decode($userinfo['nickname']);
        $time = pdo_fetchcolumn("select sum(`time`) as `time` from " . tablename($this->t_userlooktime) . " where weid = :weid AND uid = :uid AND `date` >= :starttime AND `date` <= :endtime ", array(':weid' => $_W['uniacid'], ':uid' => $userid, ':starttime' => date('Ymd', strtotime('this week Monday', time())), ':endtime' => date('Ymd', strtotime('this week Sunday', time()))));
        $time = ceil($time / 60);//换算成分钟
        $weeklist['looktime'] = $time;
        //获取每周排行
        $week_contion = " ul.weid = :weid AND ul.date >= :starttime AND u.status = :status AND ul.date <= :endtime ";
        $week_params = [':weid' => $_W['uniacid'], ':starttime' => date('Ymd', strtotime('this week Monday', time())), ':endtime' => date('Ymd', strtotime('this week Sunday', time())), ':status' => 1];
        $weeklist['list'] = pdo_fetchall("select u.headimg,u.nickname,u.myheaderimg,u.id,sum(time) as time from " . tablename($this->t_userlooktime) . " ul JOIN " . tablename($this->t_user) . " u ON ul.uid = u.id where " . $week_contion . "group by ul.uid  order BY sum(time) DESC   LIMIT 0,20", $week_params);
        foreach ($weeklist['list'] as $k => $v) {
            if (!empty($v['myheaderimg'])) {
                $weeklist['list'][$k]['headerimg'] = $_W['attachment'] . $v['myheaderimg'];
            } else {
                $weeklist['list'][$k]['headerimg'] = $v['headimg'];
            }
            unset($weeklist['list'][$k]['headimg']);
            unset($weeklist['list'][$k]['myheaderimg']);
            $weeklist['list'][$k]['looktime'] = ceil($v['time'] / 60);
            unset($weeklist['list'][$k]['time']);
            $weeklist['list'][$k]['nickname'] = json_decode($weeklist['list'][$k]['nickname']);
        }
        $weeklistid = array_column($weeklist['list'], 'id');
        if (!in_array($userinfo['id'], $weeklistid)) {
            $weeklist['isrank'] = 0;
        } else {
            $weeklist['isrank'] = array_search($userinfo['id'], $weeklistid) + 1;
        }
        //月排行
        $total_looktimes = pdo_fetchcolumn("select `time` from " . tablename($this->t_userlooktimes) . "where weid = :weid AND uid = :uid AND `date` = :date", array(':weid' => $_W['uniacid'], ':uid' => $userinfo['id'], ':date' => date('Ym01', time())));
        $total_looktimes = ceil($total_looktimes / 60);//换算成分钟
        $totallist['looktime'] = $total_looktimes;
        $total_contion = " uls.weid = :weid AND uls.date = :date AND u.status = :status ";
        $total_params = [':weid' => $_W['uniacid'], ':date' => date('Ym01', time()), ':status' => 1];
        $totallist['list'] = pdo_fetchall("select uls.time,u.headimg,u.nickname,u.myheaderimg,uls.uid from " . tablename($this->t_userlooktimes) . " uls JOIN " . tablename($this->t_user) . " u ON uls.uid = u.id where " . $total_contion . " group by uls.uid order by uls.time DESC limit 0,20", $total_params);
        foreach ($totallist['list'] as $k => $v) {
            if (!empty($v['myheaderimg'])) {
                $totallist['list'][$k]['headerimg'] = $_W['attachment'] . $v['myheaderimg'];
            } else {
                $totallist['list'][$k]['headerimg'] = $v['headimg'];
            }
            unset($totallist['list'][$k]['headimg']);
            unset($totallist['list'][$k]['myheaderimg']);
            $totallist['list'][$k]['looktime'] = ceil($v['time'] / 60);
            unset($totallist['list'][$k]['time']);
            $totallist['list'][$k]['nickname'] = json_decode($totallist['list'][$k]['nickname']);
        }
        $totallistid = array_column($totallist['list'], 'uid');
        if (!in_array($userinfo['id'], $totallistid)) {
            $totallist['isrank'] = 0;
        } else {
            $totallist['isrank'] = array_search($userinfo['id'], $totallistid) + 1;
        }
        return $this->result(0, '', array('userinfo' => $userinfo, 'weeklist' => $weeklist, 'totallist' => $totallist));
    }
    /*public function checkeduser($uid){
        $info = pdo_get($this->t_user,array('id'=>$uid),['status']);
        if($info['status'] == 0){
            return false;
        }else{
            return true;
        }
    }*/
    //任务列表
    public function doPageTask()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户的id', ['code' => 3001, 'msg' => '未获取到用户id']);
        }
        //用户兑换币数量
        $userinfo = pdo_get($this->t_user, array('id' => $uid), array('card', 'myheaderimg', 'phone'));
        if (!empty($userinfo['myheaderimg'])) {
            $userinfo['issetheaderimg'] = 1;
        } else {
            $userinfo['issetheaderimg'] = 2;
        }
        if (!empty($userinfo['phone'])) {
            $userinfo['issetuserinfo'] = 1;
        } else {
            $userinfo['issetuserinfo'] = 2;
        }
        //去配置信息
        $config = $this->module['config'];
        $configinfo['lstatus'] = $config['lstatus'];
        if ($configinfo['lstatus']) {//签到奖励设置
            $configinfo['lnum'] = $config['lnum'];
            $configinfo['lday'] = $config['lday'];
            $configinfo['ldnum'] = $config['ldnum'];
        }
        $configinfo['sstatus'] = $config['sstatus'];
        if ($configinfo['sstatus'] == 1) {//分享设置
            $configinfo['snum'] = $config['snum'];
            $configinfo['zsnum'] = $config['zsnum'];
        }
        $configinfo['setheaderimg'] = $config['setheaderimg'];
        $configinfo['setuserinfo'] = $config['setuserinfo'];
        $configinfo['paylesson'] = $config['paylesson'];
        $configinfo['studylesson'] = $config['studylesson'];
        $configinfo['studylessonmax'] = $config['studylessonmax'];
        $configinfo['lookoldlesson'] = $config['lookoldlesson'];
        $configinfo['lookoldlessonmax'] = $config['lookoldlessonmax'];
        $configinfo['role'] = explode(';', $config['role']);
        //当天是否签到
        $logininfo = pdo_get($this->t_signin, array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01', time())));
        if ($logininfo['date'] == date('Ymd', time())) {
            $userinfo['issignin'] = 1;
        } else {
            $userinfo['issignin'] = 2;
        }
        //是否可领取当月奖励
        if ($logininfo['status'] == 0) {
            //未领取当月奖励
            $userinfo['receivesignin'] = 2;
            if ($logininfo['num'] >= $configinfo['lday']) {
                $userinfo['canreceivesignin'] = 1;
            } else {
                $userinfo['canreceivesignin'] = 2;
            }
        } else {
            //已领取
            $userinfo['receivesignin'] = 1;
        }
        $userinfo['signinnum'] = empty($logininfo['num']) ? 0 : $logininfo['num'];
        unset($userinfo['myheaderimg']);
        unset($userinfo['phone']);
        //本周回顾获得奖励次数
        $rewardnum = pdo_fetchcolumn("select sum(num) as num from " . tablename($this->t_userlooktime) . " where weid = :weid AND uid = :uid AND `date` >= :starttime AND `date` <= :endtime", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':starttime' => date('Ymd', strtotime('this week Monday', time())), ':endtime' => date('Ymd', strtotime('this week Sunday', time()))));
        $userinfo['rewardnum'] = empty($rewardnum) ? 0 : $rewardnum;
        if ($userinfo['rewardnum'] >= $config['lookoldlessonmax']) {
            $userinfo['rewardnum'] = $config['lookoldlessonmax'];
        }
        //按时上课次数
        $xhb = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_study_now) . " where uid = :uid  and createtime > :time1 and createtime < :time2 and status = 1 ", array(':uid' => $uid, ':time1' => strtotime('this week Monday', time()), ':time2' => strtotime('this week Sunday', time())));
        $userinfo['ontimelesson'] = empty($xhb) ? 0 : $xhb;
        //分享成功次数
        $sharenum = pdo_fetchcolumn("select COUNT(*) from " . tablename("goouc_class_usershar") . ' where uid = :uid and `date` = :time1 ', array(':uid' => $uid, ':time1' => date('Ymd', time())));
        $userinfo['sharenum'] = empty($sharenum) ? 0 : $sharenum;
        if ($userinfo['sharenum'] >= $config['zsnum']) {
            $userinfo['sharenum'] = $config['zsnum'];
        }
        return $this->result(0, '看数据', ['userinfo' => $userinfo, 'configinfo' => $configinfo]);
    }

    //兑换兑课券页面数据
    public function doPageExchange()
    {
        global $_W, $_GPC;
        $list = pdo_fetchall("select * from " . tablename($this->t_cardinfo) . " where weid = :weid AND status = :status ", array(':weid' => $_W['uniacid'], ':status' => 1));
        //查询用户是否兑换过
        /*foreach($list as $k=>$v){
            $isexchange = pdo_get($this->t_user_exchange,array('weid'=>$_W['uniacid'],'uid'=>$uid,'cid'=>$v['id']));
            if(empty($isexchange)){
                $list[$k]['isexchange'] = 2;
            }else{
                $list[$k]['isexchange'] = 1;
                if($isexchange['status'] == 1){
                    $list[$k]['isuse'] = 1;
                }else{
                    $list[$k]['isuse'] = 2;
                }
            }
        }*/
        return $this->result(0, '列表', ['list' => $list]);
    }

    //使用对课券
    public function doPageDoexchange()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $cid = $_GPC['cid'];
        if (empty($uid) || empty($cid)) {
            return $this->result(1, '未获取到用户ID或要兑换的兑课券id', ['code' => 3001, 'msg' => '未获取到用户ID或要兑换的兑课券id']);
        }
        //用户信息  以及 兑课券信息
        $userinfo = pdo_get($this->t_user, array('id' => $uid));
        $cardinfo = pdo_get($this->t_cardinfo, array('id' => $cid));
        //先查询当年兑课券次数有没有超过4次
        $config = $this->module['config'];
        $has = pdo_fetchall("select * from " . tablename($this->t_user_exchange) . " where weid = :weid AND uid = :uid  AND `year` = :year", [':weid' => $_W['uniacid'], ':uid' => $uid, ':year' => date('Y', time())]);
        if (count($has) >= $config['cardnum']) {
            return $this->result(1, '当年兑换次数已达到上限', ['code' => 3001, 'msg' => '当年兑换次数已达到上限']);
        }
        if ($userinfo['card'] < $cardinfo['need']) {
            return $this->result(1, '您的兑换币不足无法兑换', ['code' => 3002, 'msg' => '您的兑换币不足无法兑换']);
        }
        $data['weid'] = $_W['uniacid'];
        $data['uid'] = $uid;
        $data['cid'] = $cid;
        $data['status'] = 2;
        $data['addtime'] = time();
        $data['year'] = date('Y', time());
        $res = pdo_insert($this->t_user_exchange, $data);
        $resid = pdo_insertid();
        $ress = pdo_query('update  ' . tablename($this->t_user) . ' set card = card -' . $cardinfo['need'] . ' where weid=:weid AND id=:id', array(':weid' => $_W['uniacid'], ':id' => $uid));
        if ($res && $ress) {
            return $this->result(0, '兑换成功', ['code' => 200, '兑换成功']);
        } else {
            if (!$res && $ress) {
                pdo_query('update  ' . tablename($this->t_user) . ' set card = card +' . $cardinfo['need'] . ' where weid=:weid AND id=:id', array(':weid' => $_W['uniacid'], ':id' => $uid));
            }
            if ($res && !$ress) {
                pdo_delete($this->t_user_exchange, array('id' => $resid));
            }
            return $this->result(1, '系统问题，兑换失败，请稍后再试', ['code' => 1001, 'msg' => '系统问题，兑换失败，请稍后再试']);
        }
    }

    //我已兑换的兑课券
    public function doPageMycard()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户ID', ['code' => 3001, 'msg' => '未获取到用户ID']);
        }
        $lessonid = $_GPC['lessonid'];
        $contion = ' ue.weid = :weid AND ue.uid = :uid AND ue.year = :year ';
        $params = array(':weid' => $_W['uniacid'], ':uid' => $uid, ':year' => date('Y', time()));
        if (!empty($lessonid)) {
            $lessoninfo = pdo_get($this->t_lesson, array('id' => $lessonid));
            $contion .= ' AND c.condition < :condition ';
            $params[':condition'] = floatval($lessoninfo['pay_money']);
        }
        $list = pdo_fetchall("select ue.id,c.end_time,c.price,c.need,c.condition,c.desc,ue.addtime,ue.status from " . tablename($this->t_user_exchange) . " ue JOIN " . tablename($this->t_cardinfo) . " c ON ue.cid = c.id where " . $contion . " order by addtime DESC", $params);
        if (empty($list)) {
            return $this->result(1, '暂无兑课券', ['code' => 3002, '暂无兑课券', 'contion' => $contion, 'params' => $params]);
        }
        foreach ($list as $k => $v) {
            $list[$k]['endtime'] = date('Y年m月d日', ($v['addtime'] + 3600 * 24 * $v['end_time']));
            if (($v['addtime'] + 3600 * 24 * $v['end_time']) < time()) {
                $list[$k]['status'] = 3;
            }
        }
        return $this->result(0, '数据', ['list' => $list]);
    }

    //课程----核心功能
    public function doPageLesson()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $lessonid = $_GPC['lessonid'];
        $config = $this->module['config'];
        if (empty($uid) || empty($lessonid)) {
            return $this->result(1, '用户id或课程id未获取到', array('code' => 3001, 'msg' => '用户id或课程id未获取到'));
        }
        $lessoninfo = pdo_get($this->t_lesson, array('id' => $lessonid), array('id', 'title', 'image', 'desc', 'paytype', 'is_only', 'is_groupbuy', 'pay_money', 'old_money', 'status', 'xhbnumber', 'voidtypeid', 'fic_study_num', 'study_num', 'teacherid', 'help_teacherid', 'is_underline', 'pay_num'));
        if (empty($lessoninfo) || $lessoninfo['status'] == 0) {
            return $this->result(1, '课程不存在或已下架', ['code' => 3002, 'msg' => '课程不存在或已下架']);
        }
        //判断有没有习题
        $practiceparam = array(':weid' => $_W['uniacid'], ':lessonid' => $lessonid, ':status' => 1, ':is_delete' => 1);
        $practiceCheck = pdo_fetch('select id from ' . tablename('goouc_class_practice') . ' where weid = :weid and lessonid = :lessonid and status = :status and is_delete = :is_delete', $practiceparam);
        $lessoninfo['practicestatus'] = $config['practice_status'];//习题开关
        if (!empty($practiceCheck)) {
            $lessoninfo['haveStatus'] = 1;
        } else {
            $lessoninfo['haveStatus'] = 2;
        }
        //处理一下讲师的信息
        $lessoninfo['teacher'] = array();
        $teacher = pdo_get($this->t_teacher, array('id' => $lessoninfo['teacherid']), array('name', 'headimg', 'desc'));
        $help_teacher = pdo_get($this->t_teacher, array('id' => $lessoninfo['help_teacherid']), array('name', 'headimg', 'desc'));
        if (!empty($teacher)) {
            if (!empty($teacher['headimg'])) {
                $teacher['headimg'] = $_W['attachurl'] . $teacher['headimg'];
            }
            $teacher['iszhu'] = 1;
            $lessoninfo['teacher'][] = $teacher;
        }
        if (!empty($help_teacher)) {
            if (!empty($help_teacher['headimg'])) {
                $help_teacher['headimg'] = $_W['attachurl'] . $help_teacher['headimg'];
            }
            $help_teacher['iszhu'] = 2;
            $lessoninfo['teacher'][] = $help_teacher;
        }
        //用户是否报名  以及已报名人数
        $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $lessonid));
        $lessoninfo['studynum'] = $lessoninfo['fic_study_num'] + $signupnum;
        //处理图片
        $lessoninfo['image'] = $_W['attachurl'] . $lessoninfo['image'];
        //获取章节信息
        $sonlistAll = pdo_fetchall("select title,id,starttime,vediotime,sontype from " . tablename($this->t_son) . " where weid = :weid and lessonid = :lessonid and status = :status  order by `orders` DESC ", array(':weid' => $_W['uniacid'], ':lessonid' => $lessoninfo['id'], ':status' => 1));
        foreach ($sonlistAll as $k => &$v) {
            if ($v['sontype'] == 4) {
                if (($v['starttime'] + $v['vediotime']) <= time()) {
                    //伪直播转为录播
                    $v['sontype'] = 2;
                    pdo_update('goouc_class_son', array('sontype' => 2), array('id' => $v['id']));
                }
            }
            if ($v['sontype'] == 1) {
                if (($v['starttime'] + 1200) < time()) {
                    //课程下架
                    pdo_update('goouc_class_son', array('status' => 2), array('id' => $v['id']));
                    unset($sonlistAll[$k]);
                }
            }
        }
        foreach ($sonlistAll as $sk => $sv) {
            $sonlist[] = $sv;
        }
        $lessoninfo['sonnum'] = count($sonlist);
        $lessoninfo['newnum'] = 0;
        if (is_array($sonlist)) {
            foreach ($sonlist as $k => $v) {
                //sontype  1：直播 2：录播 3：真直播 4:伪直播 5：真直播转的录播 6：classin直播
                if ($v['sontype'] == 1) {
                    if ($v['starttime'] > time()) {
                        $sonlist[$k]['is_start'] = 2;//直播未开课
                    }
                } elseif ($v['sontype'] == 2) {
                    $sonlist[$k]['is_start'] = 1;//录播课
                    $lessoninfo['newnum']++;
                } elseif ($v['sontype'] == 3) {
                    $sonlist[$k]['is_start'] = 3;//直播中
                } elseif ($v['sontype'] == 4) {
                    if ($v['starttime'] > time()) {
                        $sonlist[$k]['is_start'] = 2;//伪直播未开课
                    } else {
                        $sonlist[$k]['is_start'] = 3;//伪直播直播中
                    }
                } elseif ($v['sontype'] == 5) {
                    //真直播转为录播
                    $sonlist[$k]['is_start'] = 1;//录播课
                    $url = pdo_get('goouc_class_live_record', array('sonid' => $v['id'], 'weid' => $_W['uniacid']), array('duration'));
                    $sonlist[$k]['vediotime'] = $url['duration'];
                }
                //判断有没有习题
                $havepractice = pdo_get('goouc_class_practice', array('weid' => $_W['uniacid'], 'sonid' => $v['id'], 'status' => 1, 'is_delete' => 1), array('id'));
                if (empty($havepractice['id'])) {
                    $sonlist[$k]['havepractice'] = 2;//没有习题
                    $sonlist[$k]['practicestatus'] = 2;//习题没做过
                    $sonlist[$k]['dostatus'] = 2;
                } else {
                    $sonlist[$k]['havepractice'] = 1;//有习题
                    //判断习题是否做过
                    $checkPractice = pdo_fetchcolumn("select id from " . tablename('goouc_class_practice_record') . " WHERE weid = :weid AND sonid = :sonid AND uid = :uid AND status = :status limit 1", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':sonid' => $v['id'], ':status' => 1));
                    if ($checkPractice) {
                        $sonlist[$k]['practicestatus'] = 1;//习题已经做过
                    } else {
                        $sonlist[$k]['practicestatus'] = 2;//习题没做过
                    }
                    //判断是不是可以做习题
                    $checkstudy = pdo_fetchcolumn("select id FROM " . tablename('goouc_class_stady') . " where weid = :weid AND uid = :uid AND sonid = :sonid", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':sonid' => $v['id']));
                    //1可以做 2不可以做
                    if (empty($checkstudy)) {
                        $sonlist[$k]['dostatus'] = 2;
                    } else {
                        $sonlist[$k]['dostatus'] = 1;
                    }
                }
                //该章节星星数量
                $getstar = pdo_fetchcolumn("select num from " . tablename('goouc_class_user_star') . " WHERE weid = :weid AND sonid = :sonid AND uid = :uid AND status = :status ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':sonid' => $v['id'], ':status' => 1));
                $sonlist[$k]['getstar'] = empty($getstar) ? 0 : $getstar;
            }
        }
        $signup = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_signup) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $lessoninfo['id']));
        $group = [
            'list' => [],
            'userinfo' => []
        ];
        $is_underline = 0;
        if ($lessoninfo['is_underline'] == 1) {
            $phone = pdo_getcolumn('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => intval($uid)), 'phone');
            if (!empty($phone)) {
                $is_underline = pdo_getcolumn('goouc_class_lesson_underline_student', array('weid' => $_W['uniacid'], 'phone' => trim($phone), 'lesson_id' => intval($lessonid)), 'id');
            }
        }
        if ($signup || $is_underline > 0) {
            //已报名成功
            $lessoninfo['signup'] = 1;
        } else {
            //未报名
            $lessoninfo['signup'] = 2;
            //团购课程信息
            if ($lessoninfo['paytype'] == 4 && $lessoninfo['is_groupbuy'] == 1) {
                //当前用户是否参与或开团
                $arr = array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $lessonid, ':endtime' => (time() - $config['validtime'] * 3600), ':status' => 2);
                $has_group = pdo_fetch("select ug.id from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_user_group) . " ug ON ugi.groupid = ug.id where ugi.weid = :weid AND ugi.uid = :uid AND ug.lessonid = :lessonid AND ug.createtime > :endtime AND ug.status = :status", $arr);
                if (empty($has_group)) {
                    //未参与过团  也没开过团
                    $group['hasgroup'] = 2;
                    //获得这个课程可参加的团
                    $group['list'] = pdo_fetchall("select ug.*,u.headimg,u.myheaderimg,u.nickname from " . tablename($this->t_user_group) . " ug JOIN " . tablename($this->t_user) . " u ON ug.uid = u.id where ug.weid = :weid AND ug.lessonid = :lessonid AND ug.status = :status AND ug.createtime > :createtime order by ug.createtime DESC limit 0,3", array(':weid' => $_W['uniacid'], ':lessonid' => $lessonid, ':status' => 2, ':createtime' => (time() - $config['validtime'] * 3600)));
                    if (!empty($group['list'])) {
                        foreach ($group['list'] as $k => $v) {
                            if (!empty($v['myheaderimg'])) {
                                unset($group['list'][$k]['headimg']);
                                if (strpos($v['myheaderimg'], 'http') !== false) {
                                    $group['list'][$k]['headerimg'] = $v['myheaderimg'];
                                } else {
                                    $group['list'][$k]['headerimg'] = $_W['attachurl'] . $v['myheaderimg'];
                                }
                            } else {
                                $group['list'][$k]['headerimg'] = $v['headimg'];
                                unset($group['list'][$k]['headimg']);
                            }
                            //还差多少人
                            $group['list'][$k]['neednum'] = $config['groupnum'] - $v['groupnum'];
                            //结束时间
                            $group['list'][$k]['endtime'] = $v['createtime'] + 3600 * $config['validtime'];
                            $group['list'][$k]['nickname'] = json_decode($group['list'][$k]['nickname']);
                        }
                        //改课程总共有多少拼团人
                        $group['hasnum'] = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_user_group) . " ug ON ugi.groupid = ug.id where ugi.weid = :weid AND ugi.lessonid = :lessonid AND ug.createtime > :createtime AND ug.status = 2", array(':weid' => $_W['uniacid'], ':lessonid' => $lessonid, ':createtime' => (time() - 3600 * $config['validtime'])));
                    }
                } else {
                    $group['hasgroup'] = 1;
                    //拿到团信息
                    $group['userinfo'] = pdo_fetchall("select u.headimg,u.myheaderimg,ugi.isgrouper,ugi.groupid from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_user) . " u ON ugi.uid = u.id where ugi.weid = :weid AND groupid = :groupid order by ugi.isgrouper ASC", array(':weid' => $_W['uniacid'], ':groupid' => $has_group['id']));
                    if (!empty($group['userinfo'])) {
                        foreach ($group['userinfo'] as $k => $v) {
                            if (!empty($v['myheaderimg'])) {
                                if (strpos($v['myheaderimg'], 'http') !== false) {
                                    $group['userinfo'][$k]['headerimg'] = $v['myheaderimg'];
                                } else {
                                    $group['userinfo'][$k]['headerimg'] = $_W['attachurl'] . $v['myheaderimg'];
                                }
                                unset($group['userinfo'][$k]['headimg']);
                                unset($group['userinfo'][$k]['myheaderimg']);
                            } else {
                                $group['userinfo'][$k]['headerimg'] = $v['headimg'];
                                unset($group['userinfo'][$k]['headimg']);
                                unset($group['userinfo'][$k]['myheaderimg']);
                            }
                        }
                        //还差多少人
                        $group['neednum'] = $config['groupnum'] - COUNT($group['userinfo']);
                        //结束时间
                        $starttime = pdo_fetchcolumn("select createtime from " . tablename($this->t_user_group) . " where id = :id", array(':id' => $group['userinfo'][0]['groupid']));
                        $group['endtime'] = $starttime + 3600 * $config['validtime'];
                    }
                }
            }
        }
        //先查一下当年使用是否上限
        $is_max = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_exchange) . " where weid = :weid AND uid = :uid AND year = :year AND status = 1", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':year' => date('Y', time())));
        if ($is_max >= $config['cardnum']) {
            //当年使用兑课券已上线
            $card['ismax'] = 1;
            $card['can_use_card_num'] = 0;
        } else {
            //获取用户是否有可用的兑课券
            $card['ismax'] = 2;
            $params = array(':weid' => $_W['uniacid'], ':condition' => floatval($lessoninfo['pay_money']), ':uid' => $uid, ':year' => date('Y', time()));
            $can_use_card_list = pdo_fetchall("select * from " . tablename($this->t_user_exchange) . " ue JOIN " . tablename($this->t_cardinfo) . " c ON ue.cid = c.id where ue.weid = :weid AND ue.status = 2 AND c.condition < :condition AND ue.uid = :uid AND ue.year = :year AND c.status = 1", $params);
            foreach ($can_use_card_list as $k => $v) {
                $endtime = $v['addtime'] + ($v['end_time'] * 24 * 60 * 60);
                if ($endtime < time()) {
                    unset($can_use_card_list[$k]);
                }
            }
            $card['can_use_card_num'] = count($can_use_card_list);
        }
        //相关课程
        $aboutlesson = pdo_fetchall("SELECT l.id,`title`,`image`,`paytype`,`xhbnumber`,`pay_money`,`old_money`,`is_only`,`is_groupbuy`,`study_num`,`pay_num`,`fic_study_num` FROM " . tablename($this->t_lesson) . " l WHERE l.weid = :weid AND l.status = 1 and l.recommend  = 1 AND id != :id AND l.voidtypeid = :voidtypeid ORDER BY l.order DESC LIMIT 0,4 ", array(':weid' => $_W['uniacid'], ':voidtypeid' => $lessoninfo['voidtypeid'], ':id' => $lessoninfo['id']));
        foreach ($aboutlesson as $k => $v) {
            if ($_W['uniacid'] == 20) {
                $aboutlesson[$k]['image'] = $this->qiniu_url . $v['image'];
            } else {
                $aboutlesson[$k]['image'] = $_W['attachurl'] . $v['image'];
            }
            $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $v['id']));
            $aboutlesson[$k]['studynum'] = $v['fic_study_num'] + $signupnum;
        };
        //推荐课程
        $recommendlesson = pdo_fetchall("SELECT l.id,`title`,`image`,`paytype`,`xhbnumber`,`pay_money`,`old_money`,`is_only`,`is_groupbuy`,`study_num`,`pay_num`,`fic_study_num` FROM " . tablename($this->t_lesson) . " l WHERE l.weid = :weid AND l.status = 1 and l.recommend  = 1 ORDER BY l.order DESC LIMIT 0,4 ", array(':weid' => $_W['uniacid']));
        foreach ($recommendlesson as $k => $v) {
            // $recommendlesson[$k]['image'] = $_W['attachurl'].$v['image'];
            // $recommendlesson[$k]['image'] = $this->qiniu_url.$v['image'];
            if ($_W['uniacid'] == 20) {
                $recommendlesson[$k]['image'] = $this->qiniu_url . $v['image'];
            } else {
                $recommendlesson[$k]['image'] = $_W['attachurl'] . $v['image'];
            }
            $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $v['id']));
            $recommendlesson[$k]['studynum'] = $v['fic_study_num'] + $signupnum;
        }
        return $this->result(0, '看数据', ['lessoninfo' => $lessoninfo, 'sonlist' => $sonlist, 'group' => $group, 'card' => $card, 'progress' => 0.1, 'recommendlesson' => $recommendlesson, 'aboutlesson' => $aboutlesson, 'swooleip' => $config['ip']]);
    }

    //我的课程
    public function doPageMylesson()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id或课程id未获取到', array('code' => 3001, 'msg' => '用户id或课程id未获取到'));
        }
        //学习天数统计
        $day_time = pdo_get($this->t_userlooktime, array('uid' => $uid, 'date' => date('Ymd', time()), 'weid' => $_W['uniacid']));
        //连续学习天数
        $all = pdo_fetchall("select * from " . tablename($this->t_userlooktime) . " where weid = :weid AND uid = :uid order by `date` DESC ", array(':uid' => $uid, ':weid' => $_W['uniacid']));
        $continuity = 0;
        foreach ($all as $k => $v) {
            if (($all[$k]['date'] - $all[$k + 1]['date']) == 1) {
                $continuity++;
            } else {
                break;
            }
        }
        $continuity++;
        //总学习天数
        $total_day = count($all);
        $userinfo['day_time'] = empty($day_time) ? 0 : $day_time['time'];
        $userinfo['continuity'] = $continuity;
        $userinfo['total_day'] = $total_day;
        //获取已报名的课程
        $contion = " s.weid = :weid AND s.uid = :uid AND ss.starttime >= :time1 AND ss.starttime <= :time2 ";
        $params = [':weid' => $_W['uniacid'], ':uid' => $uid, ':time1' => mktime(0, 0, 0, date('m'), 1, date('Y')), ':time2' => mktime(23, 59, 59, date('m'), date('t'), date('Y'))];
        $list = pdo_fetchall("select s.id,s.lessonid,s.uid,l.title as ltitle,l.id as lid,ss.id as sid,ss.title as stitle,ss.starttime from " . tablename($this->t_signup) . " s LEFT JOIN " . tablename($this->t_lesson) . " l ON s.lessonid = l.id LEFT JOIN " . tablename($this->t_son) . " ss ON ss.lessonid = l.id where " . $contion, $params);
        foreach ($list as $k => $v) {
            $list[$k]['day'] = date('d', $v['starttime']);
        }
        $daylist = array_unique(array_column($list, 'day'));
        $a = [];
        foreach ($daylist as $k => $v) {
            $s = [];
            $s['day'] = $v;
            foreach ($list as $kk => $vv) {
                if ($vv['day'] == $v) {
                    if (empty($s['son'])) {
                        $s['son'][] = $vv;
                    } else {
                        array_push($s['son'], $vv);
                    }
                }
            }
            array_push($a, $s);
        }
        //已购的全部课程
        $subjectid = $_GPC['subjectid'];
        if (empty($subjectid)) {
            $buylesson = pdo_fetchall("select l.id,l.title,l.image,l.fic_study_num,l.study_num,l.pay_num,l.paytype,l.pay_money,l.old_money,l.xhbnumber from " . tablename($this->t_signup) . " s LEFT JOIN " . tablename($this->t_lesson) . " l ON s.lessonid = l.id where s.weid = :weid and s.uid = :uid AND l.id is not null ", array(':weid' => $_W['uniacid'], ':uid' => $uid));
        } else {
            $buylesson = pdo_fetchall("select l.id,l.title,l.image,l.fic_study_num,l.study_num,l.pay_num,l.paytype,l.pay_money,l.old_money,l.xhbnumber from " . tablename($this->t_signup) . " s LEFT JOIN " . tablename($this->t_lesson) . " l ON s.lessonid = l.id where s.weid = :weid and s.uid = :uid AND l.subjectid = :subjectid AND l.id is not null ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':subjectid' => $subjectid));
        }
        foreach ($buylesson as $k => $v) {
            // $buylesson[$k]['image'] = $_W['attachurl'].$v['image'];
            // $buylesson[$k]['image'] = $this->qiniu_url.$v['image'];
            if ($_W['uniacid'] == 20) {
                $buylesson[$k]['image'] = $this->qiniu_url . $v['image'];
            } else {
                $buylesson[$k]['image'] = $_W['attachurl'] . $v['image'];
            }
            $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $v['id']));
            $buylesson[$k]['studynum'] = $v['fic_study_num'] + $signupnum;
            $time = pdo_fetchcolumn("select study_time from " . tablename($this->t_user_study_speed) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid order by study_time DESC ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $v['id']));
            if (!empty($time)) {
                $buylesson[$k]['studytime'] = date('Y年m月d日 H:i:s', $time);
            } else {
                $buylesson[$k]['studytime'] = 0;
            }
            if ($v['is_only'] == 1) {
                $son_vediotime = pdo_fetchcolumn("select vediotime from " . tablename($this->t_son) . " where lessonid = :lessonid ", array(':lessonid' => $v['id']));
                if ($son_vediotime == 0.00) {
                    $buylesson[$k]['speed'] = 0;
                } else {
                    $buylesson[$k]['speed'] = $buylesson[$k]['speed'] / $son_vediotime;
                }
            } else {
                $study_total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_study_speed) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $v['id']));
                $total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_son) . " where  lessonid = :lessonid ", array(':lessonid' => $v['id']));
                if (empty($study_total) || empty($total)) {
                    $buylesson[$k]['speed'] = 0;
                } else {
                    $buylesson[$k]['speed'] = $study_total / $total;
                }
            }
        }
        //最近学习的一个课程
        $nearlesson = pdo_fetch("select l.id,l.title,l.image,l.fic_study_num,l.pay_num,l.study_num,l.paytype,l.pay_money,l.old_money,l.xhbnumber,uss.study_time,l.is_only from " . tablename($this->t_user_study_speed) . " uss JOIN " . tablename($this->t_lesson) . " l ON uss.lessonid = l.id where uss.weid = :weid AND uss.uid = :uid order by uss.study_time DESC ", array(':weid' => $_W['uniacid'], ':uid' => $uid));
        if (!empty($nearlesson)) {
            // $nearlesson['image'] = $_W['attachurl'].$nearlesson['image'];
            // $nearlesson['image'] = $this->qiniu_url.$nearlesson['image'];
            if ($_W['uniacid'] == 20) {
                $nearlesson['image'] = $this->qiniu_url . $nearlesson['image'];
            } else {
                $nearlesson['image'] = $_W['attachurl'] . $nearlesson['image'];
            }
            $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $nearlesson['id']));
            $nearlesson['studynum'] = $nearlesson['fic_study_num'] + $signupnum;
            if ($nearlesson['is_only'] == 1) {
                $son_vediotime = pdo_fetchcolumn("select vediotime from " . tablename($this->t_son) . " where lessonid = :lessonid ", array(':lessonid' => $nearlesson['id']));
                if ($son_vediotime == 0.00) {
                    $nearlesson['speed'] = 0;
                } else {
                    $nearlesson['speed'] = $nearlesson['speed'] / $son_vediotime;
                }
            } else {
                $study_total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_study_speed) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $nearlesson['id']));
                $total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_son) . " where  lessonid = :lessonid ", array(':lessonid' => $nearlesson['id']));
                if (empty($study_total) || empty($total)) {
                    $nearlesson['speed'] = 0;
                } else {
                    $nearlesson['speed'] = $study_total / $total;
                }
            }
        }
        $nearlesson['studytime'] = date('Y年m月d日 H:i:s', $nearlesson['study_time']);
        //返回所有学科
        $subject = pdo_getall($this->t_subject, array('weid' => $_W['uniacid'], 'status' => 1));
        return $this->result(0, '我的课程', array('list' => $a, 'userinfo' => $userinfo, 'buylesson' => $buylesson, 'nearlesson' => $nearlesson, 'subject' => $subject));
    }

    //拼团参团接口
    public function doPageGroup()
    {
        global $_W, $_GPC;
        $lessonid = $_GPC['lessonid'];
        $uid = $_GPC['uid'];
        $config = $this->module['config'];
        if (empty($lessonid)) {
            return $this->result(1, '课程id未获取到', array('code' => 3001, 'msg' => '课程id未获取到'));
        }
        $is_pay = pdo_get($this->t_order, array('userid' => $uid, 'dataid' => $lessonid, 'weid' => $_W['uniacid'], 'order_status' => 1));
        //create创建团  join  参加团  more获取所有的可参与的团的列表
        $op = empty($_GPC['op']) ? 'create' : $_GPC['op'];
        if ($op == 'more') {
            $list = pdo_fetchall("select ug.*,u.headimg,u.myheaderimg,u.nickname from " . tablename($this->t_user_group) . " ug JOIN " . tablename($this->t_user) . " u ON ug.uid = u.id where ug.weid = :weid AND ug.lessonid = :lessonid AND ug.status = :status AND ug.createtime > :createtime order by ug.createtime DESC ", array(':weid' => $_W['uniacid'], ':lessonid' => $lessonid, ':status' => 2, ':createtime' => (time() - $config['validtime'] * 3600)));
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    if (!empty($v['myheaderimg'])) {
                        unset($list[$k]['headimg']);
                        $list[$k]['headerimg'] = $_W['attachurl'] . $v['myheaderimg'];
                        if (strpos($v['myheaderimg'], 'http') !== false) {
                            $list[$k]['headerimg'] = $v['myheaderimg'];
                        } else {
                            $list[$k]['headerimg'] = $_W['attachurl'] . $v['myheaderimg'];
                        }
                    } else {
                        $list[$k]['headerimg'] = $v['headimg'];
                        unset($list[$k]['headimg']);
                    }
                    //还差多少人
                    $list[$k]['neednum'] = $config['groupnum'] - $v['groupnum'];
                    //结束时间
                    $list[$k]['endtime'] = $v['createtime'] + 3600 * $config['validtime'];
                    $list['list'][$k]['nickname'] = json_decode($list['list'][$k]['nickname']);
                }
                return $this->result(0, '团列表', $list);
            } else {
                return $this->result(1, '暂无可参与的团', array('code' => 3002, 'msg' => '暂无可参与的团'));
            }
        } elseif ($op == 'create') {
            $uid = $_GPC['uid'];
            if (empty($uid)) {
                return $this->result(1, '用户id未获取到', array('code' => 3003, 'msg' => '用户id未获取到'));
            }
            if (!empty($is_pay)) {
                return $this->result(1, '您已经购买过该课程了', '');
            }
            $res = $this->userpay($uid, $lessonid, 2, 0);
            if ($res['code'] == 200) {
                return $this->result(0, '支付参数', $res);
            } else {
                return $this->result(1, '请求支付失败', ['uid' => $uid, 'res' => $res]);
            }
        } elseif ($op == 'join') {
            $uid = $_GPC['uid'];
            $groupid = $_GPC['groupid'];
            if (empty($uid) || empty($groupid)) {
                return $this->result(1, '用户id或要参加团的id未获取到', array('code' => 3003, 'msg' => '用户id或要参加团的id未获取到'));
            }
            if (!empty($is_pay)) {
                return $this->result(1, '您已经购买过该课程了', '');
            }
            $group_status = pdo_get($this->t_user_group, array('id' => $groupid));
            if ($group_status['status'] == 1) {
                return $this->result(1, '该团已满员', ['code' => 3004, 'msg' => '该团已满员']);
            } else {
                $res = $this->userpay($uid, $lessonid, 3, $groupid);
                if ($res['code'] == 200) {
                    return $this->result(0, '支付参数', $res);
                } else {
                    return $this->result(1, '请求支付失败', ['uid' => $uid, 'res' => $res]);
                }
            }
        }
    }

    //报名
    public function doPageSignup()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $op = empty($_GPC['op']) ? 'free' : $_GPC['op'];
        $uid = $_GPC['uid'];
        $userinfo = pdo_get($this->t_user, array('id' => $uid));
        $lessonid = $_GPC['lessonid'];
        $lessoninfo = pdo_get($this->t_lesson, array('id' => $lessonid));
        if (empty($uid) || empty($lessonid)) {
            return $this->result(1, '参数不够', ['code' => 3001, 'msg' => '参数不够']);
        }
        if ($op == 'free') {
            if ($lessoninfo['paytype'] == 2) {
                $data = array('weid' => $_W['uniacid'], 'uid' => $uid, 'lessonid' => $lessonid, 'type' => 2, 'createtime' => time());
                $res = pdo_insert($this->t_signup, $data);
                if ($res) {
                    //将课程学习人数+1
                    pdo_query("update " . tablename($this->t_lesson) . " set pay_num = study_num + 1 where id = :id", array(':id' => $lessonid));
                    return $this->result(0, '报名成功', ['code' => 200, 'msg' => '报名成功']);
                } else {
                    return $this->result(1, '报名失败', ['code' => 1001, 'msg' => '报名失败']);
                }
            } else {
                return $this->result(1, '你是怎么跑到免费里面的', ['code' => 3002, 'msg' => '你是怎么跑到免费里面的']);
            }
        } elseif ($op == 'xhb') {
            if ($lessoninfo['paytype'] == 3) {
                if ($userinfo['card'] < $lessoninfo['xhbnumber']) {
                    return $this->result(1, '您的兑换币不足', ['code' => 3002, 'msg' => '您的兑换币不足']);
                } else {
                    $res = pdo_query("update " . tablename($this->t_user) . " set card = card - " . $lessoninfo['xhbnumber'] . " where id = :id ", array(':id' => $uid));
                    if ($res) {
                        $data = array('weid' => $_W['uniacid'], 'uid' => $uid, 'lessonid' => $lessonid, 'type' => 3, 'xhbnumber' => $lessoninfo['xhbnumber'], 'createtime' => time());
                        $res = pdo_insert($this->t_signup, $data);
                        if ($res) {
                            pdo_query("update " . tablename($this->t_lesson) . " set study_num = study_num + 1 where id = :id", array(':id' => $lessonid));
                            return $this->result(0, '报名成功', ['code' => 200, 'msg' => '报名成功']);
                        } else {
                            return $this->result(1, '报名失败', ['code' => 1001, 'msg' => '报名失败']);
                        }
                    } else {
                        return $this->result(1, '扣除兑换币失败', ['code' => 1002, 'msg' => '扣除兑换币失败']);
                    }
                }
            } else {
                return $this->result(1, '你是怎么跑到兑换币里面的', ['code' => 3002, 'msg' => '你是怎么跑到兑换币里面的']);
            }
        } elseif ($op == 'rmb') {
            //这个购买为直接购买
            if ($lessoninfo['paytype'] == 4) {
                //是否选择使用兑课券
                $usercardid = $_GPC['usercardid'];
                if (empty($usercardid)) {
                    $res = $this->userpay($uid, $lessonid);
                    if ($res['code'] == 200) {
                        return $this->result(0, '请求支付参数成功', $res);
                    } else {
                        return $this->result(1, '请求支付失败', ['uid' => $uid]);
                    }
                } else {
                    $cardinfo = pdo_fetch("select c.price,c.id as cid,c.condition,ue.status,ue.year from " . tablename($this->t_user_exchange) . " ue JOIN " . tablename($this->t_cardinfo) . " c ON ue.cid = c.id where ue.id = :id ", array(':id' => $usercardid));
                    $is_max = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_exchange) . " where weid = :weid AND uid = :uid AND year = :year AND status = 1", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':year' => date('Y', time())));
                    if ($cardinfo['condition'] > $lessoninfo['pay_money']) {
                        return $this->result(1, '未达到使用条件', ['code' => 3002, 'msg' => '不满足使用条件']);
                    } elseif ($cardinfo['status'] == 1) {
                        return $this->result(1, '兑课券已经使用过不能重复使用', ['code' => 3003, 'msg' => '兑课券已经使用过不能重复使用']);
                    } elseif (($cardinfo['addtime'] + ($cardinfo['end_time'] * 24 * 60 * 60)) > time()) {
                        return $this->result(1, '兑课券已经过期', ['code' => 3004, 'msg' => '兑课券已经过期']);
                    } elseif ($is_max >= $config['cardnum']) {
                        return $this->result(1, '当年使用已达到上限', ['code' => 3005, 'msg' => '当年使用已达到上限']);
                    }
                    //可以使用兑课券购买课程了
                    $res = $this->userpay($uid, $lessonid, 4, 0, $usercardid);
                    if ($res['code'] == 200) {
                        return $this->result(0, '请求支付参数成功', $res);
                    } else {
                        return $this->result(1, '请求支付失败', ['code' => 1001, 'msg' => '请求支付失败', 'message' => $res]);
                    }
                }
            } else {
                return $this->result(1, '你是怎么跑到付费里面的', ['code' => 3003, 'msg' => '你是怎么跑到付费里面的']);
            }
        }
    }

    //观看已报名课程 --- 视频链接
    public function doPageStudy()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $sonid = $_GPC['sonid'];
        $config = $this->module['config'];
        $aliyunVod = new AliyunVod($config['regionId'], $config['AccessKeyID'], $config['AccessKeySecret']);
        if (empty($uid) || empty($sonid)) {
            return $this->result(1, '未获取到用户ID或要播放的章节ID', ['code' => 3001, 'msg' => '未获取到用户ID或要播放的章节ID']);
        }
        $soninfo = pdo_get($this->t_son, array('id' => $sonid, 'status' => 1));
        if (empty($soninfo)) {
            return $this->result(1, '章节内容不存在', ['code' => 3002, 'msg' => '章节内容不存在']);
        }
        //判断视频状态
        if ($soninfo['sontype'] == 1) {
            //直播老师未开始直播
            $sinfo['startstatus'] = 2;//未开课
        } elseif ($soninfo['sontype'] == 3) {
            //直播中的  有推流地址
            $sinfo['startstatus'] = 3;//直播中
            pdo_query("update " . tablename($this->t_son) . " set num = num + 1 where id = :id", array(':id' => $sonid));
            $sinfo['url'] = unserialize($soninfo['broad_url'])['rtmpurl'];
        } elseif ($soninfo['sontype'] == 4) {
            //伪直播
            if ($soninfo['starttime'] > time()) {
                //伪直播未开始
                $sinfo['startstatus'] = 2;
            } elseif ($soninfo['starttime'] < time() && ($soninfo['starttime'] + $soninfo['vediotime']) > time()) {
                //伪直播中的课程
                $sinfo['startstatus'] = 4;
                pdo_query("update " . tablename($this->t_son) . " set num = num + 1 where id = :id", array(':id' => $sonid));
                $video = $aliyunVod->getPlayInfo($soninfo['key']);
                $sinfo['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                $sinfo['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                $sinfo['img'] = $video->VideoBase->CoverURL;
            } else {
                //伪直播结束的课程  变成录播课程
                $sinfo['startstatus'] = 1;
                pdo_query("update " . tablename($this->t_son) . " set num = num + 1 where id = :id", array(':id' => $sonid));
                $video = $aliyunVod->getPlayInfo($soninfo['key']);
                $sinfo['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                $sinfo['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                $sinfo['img'] = $video->VideoBase->CoverURL;
            }
        } elseif ($soninfo['sontype'] == 5) {
            //获取视频url
            $sinfo['startstatus'] = 1;//录播课程
            $url = pdo_get('goouc_class_live_record', array('sonid' => $sonid, 'weid' => $_W['uniacid']), array('m3u8', 'duration'));
            $sinfo['url'] = 'https://' . $config['bucketname'] . '.' . $config['endpoint'] . '/' . $url['m3u8'];
            $sinfo['time'] = $url['duration'];
            //真直播结束销毁聊天室
            $roomid = pdo_get('goouc_class_jg_room', array('weid' => $_W['uniacid'], 'sonid' => $sonid), array('roomid'));
            if ($roomid['roomid']) {
                $config = $this->module['config'];
                $appkey = $config['jmkey'];
                $appsecret = $config['jmsecret'];
                $client = new JMessage($appkey, $appsecret);
                $room = new ChatRoom($client);
                $room->delete($roomid['roomid']);
            }
        } elseif ($soninfo['sontype'] == 6) {
            $sinfo['startstatus'] = 3;//classin直播中
            $sinfo['url'] = unserialize($soninfo['live_url'])['rtmpurl'];
        } else {
            //录播课程
            $sinfo['startstatus'] = 1;//录播课程
            pdo_query("update " . tablename($this->t_son) . " set num = num + 1 where id = :id", array(':id' => $sonid));
            $video = $aliyunVod->getPlayInfo($soninfo['key']);
            $sinfo['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
            $sinfo['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
            $sinfo['img'] = $video->VideoBase->CoverURL;
        }
        //只有真直播和伪直播：极光聊天室:看用户是否注册了极光，没有的话注册
        //检测表里是否有该用户
        if ($config['jmkey'] && $config['jmsecret']) {
            if ($soninfo['sontype'] == 3 || $soninfo['sontype'] == 4 || $soninfo['sontype'] == 6) {
                $checkJmU = pdo_get('goouc_class_jg_user', array('uid' => $uid, 'weid' => $_W['uniacid']), array('id', 'username', 'password'));
                if (empty($checkJmU['id'])) {
                    //注册用户
                    $appkey = $config['jmkey'];
                    $appsecret = $config['jmsecret'];
                    $client = new JMessage($appkey, $appsecret);
                    $user = new User($client);
                    $username = 'Jm' . $this->getRandomStr(3) . $uid;
                    $password = rand(100000, 999999);
                    $response = $user->register($username, $password);
                    if ($response['http_code'] == 201) {
                        //存表
                        $Jmdata = [
                            'weid' => $_W['uniacid'],
                            'uid' => $uid,
                            'username' => $username,
                            'password' => $password,
                            'ctime' => time()
                        ];
                        pdo_insert('goouc_class_jg_user', $Jmdata);
                        $sinfo['jmuname'] = $username;
                        $sinfo['jmupwd'] = $password;
                    }
                } else {
                    $sinfo['jmuname'] = $checkJmU['username'];
                    $sinfo['jmupwd'] = $checkJmU['password'];
                }
                //取聊天室roomid
                $roomid = pdo_get('goouc_class_jg_room', array('weid' => $_W['uniacid'], 'sonid' => $sonid), array('roomid'));
                $sinfo['roomid'] = $roomid['roomid'];
            }
        }
        return $this->result(0, '更新一下列表记录', array('soninfo' => $sinfo));
    }

    //咨询页面
    public function doPageConsultation()
    {
        global $_W, $_GPC;
        $citylist = pdo_get($this->t_city, array('weid' => $_W['uniacid'], 'status' => 1));
        if (empty($citylist)) {
            $citylist = pdo_get($this->t_city, array('weid' => $_W['uniacid']));
        }
        $citylist['image'] = $_W['attachurl'] . $citylist['image'];
        return $this->result(0, '城市接口数据', array('citylist' => $citylist));
    }

    //分享的接口
    public function doPageSharnew()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $sharset = array('nstatus' => $config['nstatus'], 'nnum' => $config['nnum'], 'lstatus' => $config['lstatus'], 'lnum' => $config['lnum'], 'sstatus' => $config['sstatus'], 'snumber' => $config['snumber'], 'snum' => $config['snum'], 'zsnum' => $config['zsnum']);
        $uid = intval($_GPC['uid']);
        if (empty($uid)) {
            return $this->result(1, '未获取到用户ID', ['code' => 3001, 'msg' => '未获取到用户ID']);
        }
        $op = trim($_GPC['op']);
        if ($op == 'shar') {
            $bcode = $_GPC['code'];
            $info = json_decode($this->getopenidnew($bcode));
            //获取unionId进行比较
            $userinfo = pdo_fetch("SELECT `id` FROM " . tablename($this->t_user) . " WHERE openid = :openid AND weid = :weid", array(':openid' => $info->openid, ':weid' => $_W['uniacid']));
            if (empty($userinfo)) {
                // 生成一条新用户
                $new_user = array('weid' => $_W['uniacid'], 'openid' => $info->openid, 'new_status' => 1, 'createtime' => time());
                pdo_insert($this->t_user, $new_user);
                $buid = pdo_insertid();
            } else {
                $buid = $userinfo['id'];
            }
            $day_has1 = pdo_get('goouc_class_usershar', array('weid' => $_W['uniacid'], 'uid' => $uid, 'buid' => $buid, 'date' => date('Ymd')));
            $day_has2 = pdo_get('goouc_class_usershar', array('weid' => $_W['uniacid'], 'uid' => $buid, 'buid' => $uid, 'date' => date('Ymd')));
            if ($day_has1 || $day_has2) {
                return $this->result(1, '两位已经得到过相应的奖励');
            } else {
                // 在分享表生成分享与被分享的关系数据
                $shar = array('weid' => $_W['uniacid'], 'uid' => $uid, 'buid' => $buid, 'date' => date('Ymd'));
                pdo_insert('goouc_class_usershar', $shar);
                //判断是否给他们加听课券
                $from_user_num = pdo_fetchcolumn("select count(*) from " . tablename('goouc_class_usershar') . " where weid=:weid AND uid=:uid AND date=:date AND buid != 0", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':date' => date('Ymd')));
                $to_user_num = pdo_fetchcolumn("select count(*) from " . tablename('goouc_class_usershar') . " where weid=:weid AND buid=:buid AND date=:date", array(':weid' => $_W['uniacid'], ':buid' => $buid, ':date' => date('Ymd')));
                //判断分享者今天分享的总共得到多少张
                if ($from_user_num * $sharset['snum'] <= 1 * $sharset['zsnum']) {
                    //给分享者添加
                    $res = pdo_query('update  ' . tablename('goouc_class_user') . ' set card = card +' . $sharset['snum'] . ' where weid=:weid AND id=:id', array(':weid' => $_W['uniacid'], ':id' => $uid));
                }
                if ($to_user_num * $sharset['snum'] <= 1 * $sharset['zsnum']) {
                    //给分享者添加
                    $res = pdo_query('update  ' . tablename('goouc_class_user') . ' set card = card +' . $sharset['snum'] . ' where weid=:weid AND id=:id', array(':weid' => $_W['uniacid'], ':id' => $buid));
                    $message = array('code' => 1, 'messs' => '获取听课券成功', 'num' => $sharset['snum']);
                    return $this->result(0, '已获得听课券', $message);
                } else {
                    $message = array('code' => 1, 'messs' => '当天获得听课券已达到上限');
                    return $this->result(1, '当天获得听课券已达到上限', $message);
                }
                return $this->result(0, '分享加', array($from_user_num * $sharset['snum'], $sharset['zsnum'],));
            }
        } elseif ($op == 'checke') {
            //有分享举动  先发奖励
            $usershar = pdo_get('goouc_class_usershar', array('weid' => $_W['uniacid'], 'uid' => $uid, 'buid' => 0, 'date' => date('Ymd', time())));
            if (empty($usershar)) {
                $dataa['weid'] = $_W['uniacid'];
                $dataa['uid'] = $uid;
                $dataa['buid'] = 0;
                $dataa['date'] = date('Ymd', time());
                $dataa['num'] = 1;
                $dataa['cardnum'] = $sharset['snum'];
                pdo_insert('goouc_class_usershar', $dataa);
                pdo_query('update ' . tablename('goouc_class_user') . " set card = card + " . $sharset['snum'] . " where id=:id AND weid=:weid", array(':id' => $uid, ':weid' => $_W['uniacid']));
                return $this->result(0, '分享者得到听课券', array('code' => 1, 'num' => $sharset['snum']));
            } else {
                if ($usershar['num'] >= $sharset['snumber']) {
                    return $this->result(1, '上限了', array('code' => 1, 'num' => $sharset['snum']));
                    exit;
                } else {
                    //分享获取没有达到上限
                    $dataa['num'] = $usershar['num'] + 1;
                    $dataa['cardnum'] = $usershar['cardnum'] + $sharset['snum'];
                    pdo_update('goouc_class_usershar', $dataa, array('id' => $usershar['id']));
                    // 给用户加听课券
                    pdo_query('update ' . tablename('goouc_class_user') . " set card = card + " . $sharset['snum'] . " where id=:id AND weid=:weid", array(':id' => $uid, ':weid' => $_W['uniacid']));
                    return $this->result(0, '分享者得到听课券', array('code' => 1, 'num' => $sharset['snum']));
                }
            }
        } elseif ($op == 'receive') {
            //先更改本月签到奖励领取设置
            $res = pdo_update('goouc_class_signin', array('status' => 1), array('uid' => $uid, 'month' => date('Ym01', time()), 'weid' => $_W['uniacid']));
            if ($res) {
                pdo_query("UPDATE " . tablename('goouc_class_user') . " SET card = card + " . $config['ldnum'] . " WHERE id = :id", array(':id' => $uid));
                return $this->result(0, '领取成功', array('csingn' => 0));//已领取 不能再领取了
            }
        }
    }

    //获取分享团数据
    public function doPageShareinfo()
    {
        global $_W, $_GPC;
        $groupid = $_GPC['groupid'];
        $uid = $_GPC['uid'];
        $config = $this->module['config'];
        $info = [];
        if (empty($uid) || empty($groupid)) {
            return $this->result(1, '没有团ID或用户ID', ['code' => 3001, 'msg' => '没有团ID或拼团ID']);
        }
        $groupinfo = pdo_get($this->t_user_group, array('id' => $groupid));
        if (empty($groupinfo)) {
            return $this->result(1, '团信息不存在', ['code' => 3002, 'msg' => '团信息不存在']);
        }
        if ($groupinfo['status'] == 1) {
            return $this->result(1, '团已完成', ['code' => 3003, 'msg' => '团已完成', 'lessonid' => $groupinfo['lessonid']]);
        }
        if (time() > $groupinfo['createtime'] + 3600 * $config['validtime']) {
            return $this->result(1, '团已过期', ['code' => 3004, 'msg' => '团已过期']);
        }
        $list = pdo_fetchall("select u.headimg,u.myheaderimg,ugi.isgrouper,ugi.groupid,u.nickname,ugi.uid from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_user) . " u ON ugi.uid = u.id where ugi.weid = :weid AND groupid = :groupid order by ugi.isgrouper ASC", array(':weid' => $_W['uniacid'], ':groupid' => $groupid));
        $listid = array_column($list, 'uid');
        if (in_array($uid, $listid)) {
            $info['ingroup'] = 1;
        } else {
            $info['ingroup'] = 2;
        }
        $lessonid = $groupinfo['lessonid'];
        $lessoninfo = pdo_get($this->t_lesson, array('id' => $lessonid), array('id', 'image', 'title', 'paytype', 'is_only', 'is_groupbuy', 'old_money', 'pay_money', 'status', 'fic_study_num', 'study_num', 'pay_num'));
        if (empty($lessoninfo) || $lessoninfo['status'] == 0) {
            return $this->result(1, '拼团课程不存在', ['code' => 3005, 'msg' => '拼团课程不存在']);
        }
        $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $lessonid));
        $lessoninfo['zstudynum'] = $signupnum + $lessoninfo['fic_study_num'];
        // $lessoninfo['image'] = $_W['attachurl'].$lessoninfo['image'];
        // $lessoninfo['image'] = $this->qiniu_url.$lessoninfo['image'];
        if ($_W['uniacid'] == 20) {
            $lessoninfo['image'] = $this->qiniu_url . $lessoninfo['image'];
        } else {
            $lessoninfo['image'] = $_W['attachurl'] . $lessoninfo['image'];
        }
        $lessoninfo['groupid'] = $groupid;
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                if (!empty($v['myheaderimg'])) {
                    $list[$k]['headerimg'] = $v['myheaderimg'];
                } else {
                    $list[$k]['headerimg'] = $v['headimg'];
                }
                if ($v['isgrouper'] == 1) {
                    $info['groupname'] = json_decode($v['nickname']);
                }
                unset($list[$k]['headimg']);
                unset($list[$k]['myheaderimg']);
                $list['list'][$k]['nickname'] = json_decode($list['list'][$k]['nickname']);
            }
            $info['list'] = $list;
            //还差多少人
            $info['neednum'] = $config['groupnum'] - COUNT($list);
            //结束时间
            $info['endtime'] = $groupinfo['createtime'] + 3600 * $config['validtime'];
        }
        return $this->result(0, '数据', ['groupinfo' => $info, 'lessoninfo' => $lessoninfo]);
    }

    //记录用户观看视频接口
    public function doPageRecord()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $sonid = $_GPC['sonid'];
        $config = $this->module['config'];
        if (empty($uid) || empty($sonid)) {
            return $this->result(1, '没有用户ID或观看视频的ID', ['code' => 3001, 'msg' => '没有用户ID或观看视频的ID']);
        }
        $speed = $_GPC['speed'];
        $op = $_GPC['op'];
        if ($op == 'review') {
            $time = $_GPC['time'];
            //录播
            $array['time'] = $time;
            $array['weid'] = $_W['uniacid'];
            $array['uid'] = $uid;
            //$array['date'] = date('Ymd',strtotime("last Sunday"));
            //改成记录当天日期
            $array['date'] = date('Ymd', time());
            $has = pdo_get($this->t_userlooktime, array('uid' => $uid, 'date' => $array['date']));
            if ($has) {
                $arr['time'] = $has['time'] + $time;
                pdo_update($this->t_userlooktime, $arr, array('uid' => $uid, 'date' => $array['date']));
            } else {
                pdo_insert($this->t_userlooktime, $array);
            }
            $arram['time'] = $time;
            $arram['weid'] = $_W['uniacid'];
            $arram['uid'] = $uid;
            $arram['date'] = date('Ym01', strtotime(date('Ymd')));
            $hasm = pdo_get($this->t_userlooktimes, array('uid' => $uid, 'date' => $arram['date'], 'weid' => $_W['uniacid']));
            if ($hasm) {
                $arrm['time'] = $hasm['time'] + $time;
                pdo_update($this->t_userlooktimes, $arrm, array('uid' => $uid, 'date' => $arram['date']));
            } else {
                pdo_insert($this->t_userlooktimes, $arram);
            }
            //记录学习时间以及学习进度
            $lessonid = pdo_fetchcolumn("select lessonid from " . tablename($this->t_son) . " where id = :id ", array(':id' => $sonid));
            $arr = [
                'weid' => $_W['uniacid'],
                'uid' => $uid,
                'lessonid' => $lessonid,
                'sonid' => $sonid,
                'study_time' => time(),
                'speed' => $speed,
            ];
            $has_speed = pdo_get($this->t_user_study_speed, array('weid' => $_W['uniacid'], 'uid' => $uid, 'sonid' => $sonid, 'lessonid' => $lessonid));
            if ($has_speed) {
                pdo_update($this->t_user_study_speed, $arr, array('id' => $has_speed['id']));
            } else {
                pdo_insert($this->t_user_study_speed, $arr);
            }
            //用户学习时长记录表
            $user_son_data = [
                'weid' => $_W['uniacid'],
                'uid' => $uid,
                'sonid' => $sonid,
                'time' => $time,
                'createtime' => time()
            ];
            pdo_insert('goouc_class_user_son_time', $user_son_data);
            return $this->result(0, '记录成功', 1);
        } elseif ($op == 'send') {
            //查询本周发送兑换币
            $has = pdo_get($this->t_userlooktime, array('uid' => $uid, 'date' => date('Ymd', time())));
            //将用户已学习课程记录到 表中
            $res = pdo_get('goouc_class_stady', array('weid' => $_W['uniacid'], 'uid' => $uid, 'sonid' => $sonid));
            $arr['weid'] = $_W['uniacid'];
            $arr['uid'] = $uid;
            $arr['sonid'] = $sonid;
            $arr['create_time'] = time();
            if ($res) {
                pdo_update('goouc_class_stady', $arr, array('id' => $res['id']));
            } else {
                pdo_insert('goouc_class_stady', $arr);
            }
            if ($has) {
                //有记录 增加一次领取记录  用户增加相应的兑换币
                //获得一周总领取次数
                $a = pdo_fetchcolumn("select sum(num) as num from " . tablename($this->t_userlooktime) . " where weid = :weid AND uid = :uid AND `date` >= :mondy AND `date` <= :endtime", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':mondy' => date('Ymd', strtotime('this week Monday', time())), ':endtime' => date('Ymd', strtotime('this week Sunday', time()))));
                if ($a < $config['lookoldlessonmax']) {
                    $res = pdo_query("update " . tablename($this->t_userlooktime) . " set num = num + 1 where id = :id ", array('id' => $has['id']));
                    if ($res) {
                        pdo_query("update " . tablename($this->t_user) . " set card = card + " . $config['lookoldlesson'] . " where id = :id ", array('id' => $uid));
                    }
                }
            } else {
                $array['time'] = 0;
                $array['weid'] = $_W['uniacid'];
                $array['uid'] = $uid;
                $array['date'] = date('Ymd', time());
                $array['num'] = 1;
                $res = pdo_insert($this->t_userlooktime, $array);
                if ($res) {
                    pdo_query("update " . tablename($this->t_user) . " set card = card + " . $config['lookoldlesson'] . " where id = :id ", array('id' => $uid));
                }
            }
        } elseif ($op == 'live') {
            //直播
            $starttime = $_GPC['starttime'];
            //计算是否观看达到15分钟以上
            $totaltime = time() - $starttime;
            if ($totaltime > 15 * 60) {
                $arr['weid'] = $_W['uniacid'];
                $arr['uid'] = $uid;
                $arr['sonid'] = $sonid;
                $arr['create_time'] = time();
                pdo_insert('goouc_class_stady', $arr);
            }
            //修改章节状态(伪直播完了，转为录播课)
            $soninfo = pdo_get('goouc_class_son', array('id' => $sonid), array('starttime', 'sontype', 'vediotime'));
            if ($soninfo['sontype'] == 4) {
                if (($soninfo['vediotime'] + $soninfo['starttime']) <= time()) {
                    $datas = ['sontype' => 2, 'status' => 1];
                    pdo_update("goouc_class_son", $datas, array('id' => $sonid));
                    //伪直播结束销毁聊天室
                    $roomid = pdo_get('goouc_class_jg_room', array('weid' => $_W['uniacid'], 'sonid' => $sonid), array('roomid'));
                    if ($roomid['roomid']) {
                        $config = $this->module['config'];
                        $appkey = $config['jmkey'];
                        $appsecret = $config['jmsecret'];
                        $client = new JMessage($appkey, $appsecret);
                        $room = new ChatRoom($client);
                        $room->delete($roomid['roomid']);
                    }
                }
            }
            $data['weid'] = $_W['uniacid'];
            $data['uid'] = $uid;
            $data['sonid'] = $sonid;
            $data['createtime'] = $starttime;
            $has = pdo_get($this->t_user_study_now, array('weid' => $_W['uniacid'], 'uid' => $uid, 'sonid' => $sonid));
            //发放兑换币 查询本周是否上限
            $xhb = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_study_now) . " where uid = :uid  and createtime > :time1 and createtime < :time2 and status = 1 ", array(':uid' => $uid, ':time1' => strtotime('this week Monday', time()), ':time2' => strtotime('this week Sunday', time())));
            if (empty($has)) {
                if ($xhb < $config['studylessonmax']) {
                    $data['status'] = 1;
                    pdo_query("update " . tablename($this->t_user) . " set card = card + " . $config['studylesson'] . " where id = :id", array(':id' => $uid));
                }
                pdo_insert($this->t_user_study_now, $data);
            } else {
                return $this->result(1, '已记录按时上课');
            }
            return $this->result(0, '看数据', $_GPC);
        }
    }

    //聊天室上传图片！！！！！
    public function doPageUploadimg()
    {
        global $_GPC, $_W;
        $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');
        $max_file_size = 2000000;
        $weid = $_W['uniacid'];
        $destination_folder = $_GPC['m'] . "/" . $weid . '/' . date('Y', time()) . '/';
        if (!is_uploaded_file($_FILES["upimg"]['tmp_name'])) {
            return $this->result(0, '图片不存在!');
        }
        $file = $_FILES["upimg"];
        if ($max_file_size < $file["size"]) {
            return $this->result(0, '文件太大!');
        }
        if (!in_array($file["type"], $uptypes)) {
            return $this->result(0, '文件类型不符!' . $file["type"]);
        }
        if (!file_exists("../attachment/" . $destination_folder)) {
            mkdir("../attachment/" . $destination_folder, 0777, true);
        }
        $filename = $file["tmp_name"];
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo['extension'];
        $imgpath = $destination_folder . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;
        $destination = "../attachment/" . $imgpath;
        if (!move_uploaded_file($filename, $destination)) {
            return $this->result(0, '移动文件出错');
        }
        $pinfo = pathinfo($destination);
        $fname = $pinfo['basename'];
        //获取七牛配置
        $setting = pdo_get('uni_settings', array('uniacid' => $weid), array('remote'));
        $config = unserialize($setting['remote']);
        $qiniuConfig = $config['qiniu'];
        if ($config['type'] == 3) {
            //上传七牛
            $accessKey = $qiniuConfig['accesskey'];
            $secretKey = $qiniuConfig['secretkey'];
            $uploadMgr = new UploadManager();
            $auth = new Auth($accessKey, $secretKey);
            // 构建 UploadManager 对象
            $bucket = $qiniuConfig['bucket'];
            // 生成上传Token
            $token = $auth->uploadToken($bucket);
            $filePath = IA_ROOT . '/attachment/' . $imgpath;
            list($ret, $err) = $uploadMgr->putFile($token, $imgpath, $filePath);
            if ($err !== null) {
                return $this->result(0, '上传失败');
            }
            //删除本地图片
            unlink(ATTACHMENT_ROOT . $destination_folder . $fname);
            echo $qiniuConfig['url'] . '/' . $destination_folder . $fname;
            exit;
        } else {
            echo $_W['attachurl'] . $destination_folder . $fname;
            exit;
        }
    }

    //上传文档！！！！！
    public function doPageUploadfile()
    {
        global $_GPC, $_W;
        $max_file_size = 2000000;
        $uptypes = array('text/plain', 'application/vnd.ms-excel', 'application/zip', 'application/x-rar-compressed', 'application/vnd.ms-powerpoint', 'application/msword', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/rtf', 'application/octet-stream');
        $weid = $_W['uniacid'];
        $destination_folder = $_GPC['m'] . "/" . $weid . '/' . date('Y', time()) . '/';
        if (!is_uploaded_file($_FILES["files"]['tmp_name'])) {
            return $this->result(1, '文档不存在!');
        }
        $file = $_FILES["files"];
        if ($max_file_size < $file["size"]) {
            return $this->result(1, '文件太大!');
        }
        if (!in_array($file["type"], $uptypes)) {
            return $this->result(1, '该类型文件不能上传!');
        }
        if (!file_exists("../attachment/" . $destination_folder . 'file/')) {
            mkdir("../attachment/" . $destination_folder . 'file/', 0777, true);
        }
        $filename = $file["tmp_name"];
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo['extension'];
        $filespath = $destination_folder . 'file/' . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;
        $destination = "../attachment/" . $filespath;
        if (!move_uploaded_file($filename, $destination)) {
            return $this->result(1, '移动文件出错!');
        }
        $pinfo = pathinfo($destination);
        $fname = $pinfo['basename'];
        //获取七牛配置
        $setting = pdo_get('uni_settings', array('uniacid' => $weid), array('remote'));
        $config = unserialize($setting['remote']);
        $qiniuConfig = $config['qiniu'];
        if ($config['type'] == 3) {
            //上传七牛
            $accessKey = $qiniuConfig['accesskey'];
            $secretKey = $qiniuConfig['secretkey'];
            $uploadMgr = new UploadManager();
            $auth = new Auth($accessKey, $secretKey);
            // 构建 UploadManager 对象
            $bucket = $qiniuConfig['bucket'];
            // 生成上传Token
            $token = $auth->uploadToken($bucket);
            $filePath = IA_ROOT . '/attachment/' . $filespath;
            list($ret, $err) = $uploadMgr->putFile($token, $filespath, $filePath);
            if ($err !== null) {
                return $this->result(0, '上传失败');
            }
            //删除本地图片
            unlink(ATTACHMENT_ROOT . $destination_folder . 'file/' . $fname);
            $fileurl = $qiniuConfig['url'] . '/' . $destination_folder . 'file/' . $fname;
            echo $fileurl;
            exit;
        } else {
            echo $_W['attachurl'] . $destination_folder . 'file/' . $fname;
            exit;
        }
    }

    //记录用户发送消息！！！！！
    public function doPageMessage()
    {
        global $_W, $_GPC;
        $data['weid'] = $_W['uniacid'];
        $data['uid'] = $_GPC['uid'];
        $data['content'] = json_encode($_GPC['content']);
        $data['sonid'] = $_GPC['sonid'];
        $data['createtime'] = time();
        $data['type'] = empty($_GPC['type']) ? 0 : $_GPC['type'];
        if ($data['type'] == 2) {
            //文档
            $data['name'] = $_GPC['title'];
            $data['size'] = $_GPC['size'];
        }
        pdo_insert($this->t_live_message, $data);
    }

    //咨询页面列表
    public function doPageCategory()
    {
        global $_W, $_GPC;
        //分类列表
        $category = pdo_fetchall("select name,id from " . tablename($this->t_category) . " where weid = :weid and status = :status", [':weid' => $_W['uniacid'], ':status' => 1]);
        return $this->result(0, '文章分类数据', ['list' => $category]);
    }

    public function doPageZixun()
    {
        global $_W, $_GPC;
        $categoryid = $_GPC['categoryid'];
        //文章列表
        $contion = ' weid = :weid and status = :status ';
        $params = [':weid' => $_W['uniacid'], ':status' => 1];
        if (!empty($categoryid)) {
            $contion .= ' and cid = :cid ';
            $params[':cid'] = $categoryid;
        } else {
            $contion .= " and recommond = 1 ";
        }
        $page = max(1, $_GPC['page']);
        $pindex = 8;
        $articlelist = pdo_fetchall("select * from " . tablename($this->t_article) . " where " . $contion . " order by `order` DESC LIMIT " . ($page - 1) * $pindex . "," . $pindex, $params);
        foreach ($articlelist as $k => $v) {
            $articlelist[$k]['image'] = $_W['attachurl'] . $v['image'];
            //$articlelist[$k]['content'] = htmlspecialchars_decode($v['content'],true);
        }
        $total = pdo_fetchcolumn("select count(*) from " . tablename($this->t_article) . " where " . $contion, $params);
        return $this->result(0, '咨询页面数据', array('total' => $total, 'articlelist' => $articlelist));
    }

    //进入聊天室获取聊天记录
    public function doPageOldmessage()
    {
        global $_W, $_GPC;
        $sonid = $_GPC['sonid'];
        if (empty($sonid)) {
            return $this->result(1, '未获取到sonid');
        }
        $list = pdo_fetchall("select u.nickname,lm.content,lm.createtime,lm.type,lm.name,lm.size from " . tablename($this->t_live_message) . " lm JOIN " . tablename($this->t_user) . " u ON lm.uid = u.id where lm.weid = :weid and lm.sonid = :sonid order by lm.createtime ASC ", [':weid' => $_W['uniacid'], ':sonid' => $sonid]);
        foreach ($list as $k => $v) {
            if ($v['type'] == 0) {
                $list[$k]['data'] = json_decode($v['content'], true);
            } elseif ($v['type'] == 1) {
                $list[$k]['img'] = json_decode($v['content'], true);
            } else {
                $list[$k]['file'] = json_decode($v['content'], true);
                $list[$k]['title'] = $v['name'];
            }
            $list['list'][$k]['nickname'] = json_decode($list['list'][$k]['nickname']);
        }
        return $this->result(0, '聊天记录', ['list' => $list]);
    }

    //获取用户拼团信息
    public function doPageUsergroup()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        if (empty($uid)) {
            return $this->result(1, '获取的UID值有问题');
        }
        //获取配置信息
        $config = $this->module['config'];
        //获取用户参加过的所有团
        $list = pdo_fetchall("select l.title,ug.groupnum,ug.createtime,ug.status,ugi.refund_status,ugi.id from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_user_group) . " ug ON ugi.groupid = ug.id JOIN " . tablename($this->t_lesson) . " l on ugi.lessonid = l.id where ugi.uid = :uid order by ugi.createtime", [':uid' => $uid]);
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                //判断团是否过期
                if ((time() - $v['createtime']) > ($config['validtime'] * 3600) && $v['groupnum'] < $config['groupnum']) {
                    //拼团失败了
                    $list[$k]['groupstatus'] = 3;
                    if ($v['refund_status'] == 1) {
                        //已退费
                        $list[$k]['refund_status'] = 1;
                    } else {
                        //未退费
                        $list[$k]['refund_status'] = 2;
                    }
                } elseif ($v['status'] == 1) {
                    //拼团成功
                    $list[$k]['groupstatus'] = 1;
                } else {
                    //拼团中
                    $list[$k]['groupstatus'] = 2;
                    $list[$k]['neednum'] = $config['groupnum'] - $v['groupnum'];
                }
            }
        }
        return $this->result(0, '我的团信息', ['list' => $list]);
    }

    //申请退款接口
    public function doPageRefund()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        $groupid = intval($_GPC['groupid']);
        if (empty($uid) || empty($groupid)) {
            return $this->result(1, '参数不和规定');
        }
        $config = $this->module['config'];
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $info = pdo_fetch("select ugi.out_trade_no,o.order_status,o.all_money,o.true_money,o.id from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_order) . " o ON ugi.out_trade_no = o.out_trade_no where ugi.id = :id ", [':id' => $groupid]);
        $out_trade_no = $info['out_trade_no'];
        $total_fee = intval($info['true_money'] * 100);
        $refund_fee = intval($info['true_money'] * 100);
        //return $this->result(0,'111',['all_money'=>$total_fee,'true_money'=>$refund_fee]);
        $input = new WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $arr = [
            'appid' => $appid,
            'appsecret' => $secret,
            'mchid' => $config['mchid'],
            'paysecret' => $config['pay_secret'],
            'sslCertPath' => IA_ROOT . '/addons/goouc_class/inc/common/wxpay/cert/cert' . $_W['uniacid'] . '.pem',
            'sslKeyPath' => IA_ROOT . '/addons/goouc_class/inc/common/wxpay/cert/key' . $_W['uniacid'] . '.pem',
        ];
        $config = new WxPayConfig($arr);
        //return $this->result(0,'看数据',['$arr'=>$arr,'config'=>$config->sslCertPath]);
        $input->SetOut_refund_no("refund" . date("YmdHis"));
        $input->SetOp_user_id($config->GetMerchantId());
        $result = WxPayApi::refund($config, $input);
        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            pdo_update($this->t_order, array('order_status' => 2, 'refundtime' => TIMESTAMP), array('id' => $info['id']));
            pdo_update($this->t_user_group_info, array('refund_status' => 1, 'createtime' => time()), ['id' => $groupid]);
            return $this->result(0, '退款成功', ['code' => 200]);
        } else {
            return $this->result(1, '退款失败', ['code' => 400, 'message' => $result]);
        }
    }

    /*
     * 新的海报接口 直接返回图片路径 有GD类库进行图片制作
     * */
    public function doPageposternews()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户ID错误');
        }
        //获取所有可用的海报设计  从中所及抽取一张
        $sql = 'select * from ' . tablename($this->t_poster) . " where weid = :weid and status = :status";
        $params = [':weid' => $_W['uniacid'], ':status' => 1];
        $poster_list = pdo_fetchall($sql, $params);
        if (empty($poster_list)) {
            return $this->result(1, '没有可用的海报');
        }
        $info = $poster_list[array_rand($poster_list)];
        $info['option'] = unserialize($info['option']);
        $uinfo = pdo_get($this->t_user, array('id' => $uid));
        /*创建相应的文件夹*/
        $pid = $info['id'];
        $qrcodeposter_path = MODULE_ROOT . '/images/Poster/qrcode/';
        if (!is_dir($qrcodeposter_path)) {
            mkdir($qrcodeposter_path, 0777, true);
        }
        $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/qrcode';
        if (!is_dir($qrcode_path)) {
            mkdir($qrcode_path, 0777, true);
        }
        $headerimg_natival = MODULE_ROOT . '/images/Poster/headerimg/header/';
        if (!is_dir($headerimg_natival)) {
            mkdir($headerimg_natival, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_poster_path = MODULE_ROOT . '/images/Poster/poster/' . $pid . '/';
        if (!is_dir($has_poster_path)) {
            mkdir($has_poster_path, 0777, true);
        }
        /*创建文件夹结束*/
        /*判断用户这个海报是否存在开始*/
        //如果不判断是否存在 一个用户值会存在一张  如果判断的话需要将海报对应日期  ？？？？？？
        /*$poster_img = MODULE_ROOT.'/images/Poster/poster/'.$pid.'/'.$uid.'_'.$pid.'.png';
        //判断示例图片是否存在
        if(file_exists($poster_img)){
            //已经生成过预览图  直接返回图片路径
            echo 123;die();
        }*/
        /*判断用户这个海报是否存在结束*/
        //继续整理需要的信息  1.获取用户总签到天数 当做学习天数
        $time = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_signin) . " where weid = :weid and uid = :uid ", array(':weid' => $_W['uniacid'], ':uid' => $uid));
        //生成海报
        $y_image = imagecreatetruecolor(616, 846);
        $bgimg_path = $_W['attachurl'] . $info['bgimg'];
        //        return $this->result(1,'路径',['path'=>$bgimg_path]);
        $b_image = imagecreatefrompng($bgimg_path);
        imagecopymerge($y_image, $b_image, 0, 0, 0, 0, imagesx($b_image), imagesy($b_image), 100);
        $font = MODULE_ROOT . '/images/simhei.ttf';
        foreach ($info['option'] as $k => $v) {
            switch ($v) {
                //开启二维码
                case 1:
                    //判断用户二维码是否存在  以及用户二维码对应这个海报的存在不存在
                    if (!file_exists(MODULE_ROOT . '/images/Poster/qrcode/qrcode/qrcode_' . $uid . '.jpg')) {
                        //用户二维码不存在，则对应海报的二维码肯定也不存在
                        //$res = json_decode($this->mkqrcodes($uid),true);
                        $appid = $_W['account']['key'];
                        $secret = $_W['account']['secret'];
                        //$appid = 'wx55fd31cd8c621d1e';
                        //$secret = 'b67423015a22cf246477bc76db3ea981';
                        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
                        $access_token = json_decode($this->curl_get($url), true)['access_token'];
                        // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
                        $data = array();
                        $data['page'] = 'pages/home/home';//路径
                        $data['scene'] = 'u=' . $uid;
                        $data = json_encode($data);
                        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
                        $da = $this->get_http_array($url, $data);
                        $file_put_result = file_put_contents(MODULE_ROOT . '/images/Poster/qrcode/qrcode/qrcode_' . $uid . '.jpg', $da);
                        if (is_error($file_put_result)) {
                            $message = ['code' => 1001, 'msg' => '写入二维码信息失败'];
                            return $this->result(1, '写入二维码信息失败', $message);
                            die();
                        } else {
                            //去制作对应还包的二维码图片
                            $res = json_decode($this->editqrcodes($uid, $pid), true);
                            if ($res['code'] != 200) {
                                $message = ['code' => 1002, 'msg' => '合并二维码失败'];
                                return $this->result(1, '合并二维码失败', $message);
                                die();
                            }
                        }
                    } else {
                        if (!file_exists(MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png')) {
                            //去做这个二维码
                            $res = json_decode($this->editqrcodes($uid, $pid), true);
                            if ($res['code'] != 200) {
                                $message = ['code' => 1002, 'msg' => '合并二维码失败'];
                                return $this->result(1, '合并二维码失败', $message);
                                die();
                            }
                        }
                    }
                    //制作成功 合并二维码与画布
                    $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png';
                    $q_image = imagecreatefrompng($qrcode_path);
                    imagecopymerge($y_image, $q_image, ($info['qrcode_left_px'] / 0.7), ($info['qrcode_top_px'] / 0.7), 0, 0, imagesx($q_image), imagesy($q_image), 100);
                    break;
                //开启用户头像
                case 2:
                    //判断用户头像是否存在  以及用户头像对应这个海报的存在不存在
                    if (!file_exists(MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png')) {
                        //还要做一个针对这个海报的头像大小
                        $res = $this->getSecond($uinfo['headimg'], MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png');
                        if (!$res) {
                            $message = array('code' => 1002, 'msg' => '下载用户头像失败');
                            return $this->result(1, '下载用户头像失败');
                            die();
                        } else {
                            $res = json_decode($this->editheadimg($uid, $pid), true);
                            if (is_error($res)) {
                                $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                                return $this->result(1, '修改用户头像大小失败');
                                die();
                            }
                        }
                    } else {
                        if (!file_exists(MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png')) {
                            //去做这个头像
                            $res = json_decode($this->editheadimg($uid, $pid), true);
                            if (is_error($res)) {
                                $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                                return $this->result(1, '修改用户头像大小失败');
                                die();
                            }
                        }
                    }
                    $headmg_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png';
                    $h_image = imagecreatefrompng($headmg_path);
                    imagecopymerge($y_image, $h_image, ($info['head_left_px'] / 0.7), ($info['head_top_px'] / 0.7), 0, 0, imagesx($h_image), imagesy($h_image), 100);
                    //合并头像到海报
                    break;
                //开启用户昵称
                case 3:
                    $nick_color = $this->hex2rgb($info['nick_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['nick_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['nick_left_px'] / 0.7);      //左边距
                    $top = ($info['nick_top_px'] + $info['nick_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, json_decode($uinfo['nickname']));
                    break;
                //开启学习天数
                case 4:
                    $nick_color = $this->hex2rgb($info['study_day_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['study_day_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['study_day_left_px'] / 0.7);      //左边距
                    $top = ($info['study_day_top_px'] + $info['study_day_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $time);
                    break;
                //开启日期
                case 5:
                    $weekarray = array("日", "一", "二", "三", "四", "五", "六");
                    $week = "星期" . $weekarray[date("w", time())];
                    $date = date('Y/m/d', time()) . $week;
                    $nick_color = $this->hex2rgb($info['date_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['date_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['date_left_px'] / 0.7);      //左边距
                    $top = ($info['date_top_px'] + $info['date_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $date);
                    break;
            }
        }
        $res = imagepng($y_image, MODULE_ROOT . '/images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png');
        $path = MODULE_URL . 'images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png';
        if ($res) {
            return $this->result(0, '海报路径', ['path' => $path]);
        } else {
            return $this->result(1, '生成海报图片失败');
        }
    }

    public function doPageposternew()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户ID错误');
        }
        //获取所有可用的海报设计  从中所及抽取一张
        $sql = 'select * from ' . tablename($this->t_poster) . " where weid = :weid and status = :status";
        $params = [':weid' => $_W['uniacid'], ':status' => 1];
        $poster_list = pdo_fetchall($sql, $params);
        if (empty($poster_list)) {
            return $this->result(1, '没有可用的海报');
        }
        $info = $poster_list[array_rand($poster_list)];
        $info['option'] = unserialize($info['option']);
        $uinfo = pdo_get($this->t_user, array('id' => $uid));
        $uinfo['nickname'] = json_decode($uinfo['nickname']);
        /*创建相应的文件夹*/
        $pid = $info['id'];
        $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/';
        if (!is_dir($qrcode_path)) {
            mkdir($qrcode_path, 0777, true);
        }
        $headerimg_natival = MODULE_ROOT . '/images/Poster/headerimg/header/';
        if (!is_dir($headerimg_natival)) {
            mkdir($headerimg_natival, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_poster_path = MODULE_ROOT . '/images/Poster/poster/' . $pid . '/';
        if (!is_dir($has_poster_path)) {
            mkdir($has_poster_path, 0777, true);
        }
        /*创建文件夹结束*/
        /*判断用户这个海报是否存在开始*/
        //如果不判断是否存在 一个用户值会存在一张  如果判断的话需要将海报对应日期  ？？？？？？
        /*$poster_img = MODULE_ROOT.'/images/Poster/poster/'.$pid.'/'.$uid.'_'.$pid.'.png';
        //判断示例图片是否存在
        if(file_exists($poster_img)){
            //已经生成过预览图  直接返回图片路径
            echo 123;die();
        }*/
        /*判断用户这个海报是否存在结束*/
        //继续整理需要的信息  1.获取用户总签到天数 当做学习天数
        $time = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_signin) . " where weid = :weid and uid = :uid ", array(':weid' => $_W['uniacid'], ':uid' => $uid));
        //生成海报
        $y_image = imagecreatetruecolor(616, 846);
        $bgimg_path = $_W['attachurl'] . $info['bgimg'];
        //        return $this->result(1,'路径',['path'=>$bgimg_path]);
        $b_image = imagecreatefrompng($bgimg_path);
        imagecopymerge($y_image, $b_image, 0, 0, 0, 0, imagesx($b_image), imagesy($b_image), 100);
        $font = MODULE_ROOT . '/images/simhei.ttf';
        foreach ($info['option'] as $k => $v) {
            switch ($v) {
                //开启二维码
                case 1:
                    //判断用户二维码是否存在  以及用户二维码对应这个海报的存在不存在
                    if (!file_exists(MODULE_ROOT . '/Qrcode/qrcode_' . $uid . '.jpg')) {
                        //用户二维码不存在，则对应海报的二维码肯定也不存在
                        $res = json_decode($this->mkqrcode($uid), true);
                        if ($res['code'] == 200) {
                            $file_put_result = file_put_contents(MODULE_ROOT . '/Qrcode/qrcode_' . $uid . '.jpg', $res['content']);
                        } else {
                            return $this->result(1, $res['msg']);
                        }
                        if (is_error($file_put_result)) {
                            $message = ['code' => 1001, 'msg' => '写入二维码信息失败'];
                            return $this->result(1, '写入二维码信息失败');
                            die();
                        } else {
                            //去制作对应还包的二维码图片
                            $res = json_decode($this->editqrcode($uid, $pid), true);
                            if ($res['code'] != 200) {
                                $message = ['code' => 1002, 'msg' => '合并二维码失败'];
                                return $this->result(1, '合并二维码失败');
                                die();
                            }
                        }
                    } else {
                        if (!file_exists(MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png')) {
                            //去做这个二维码
                            $res = json_decode($this->editqrcode($uid, $pid), true);
                            if ($res['code'] != 200) {
                                $message = ['code' => 1002, 'msg' => '合并二维码失败'];
                                return $this->result(1, '合并二维码失败');
                                die();
                            }
                        }
                    }
                    //制作成功 合并二维码与画布
                    $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png';
                    $q_image = imagecreatefrompng($qrcode_path);
                    imagecopymerge($y_image, $q_image, ($info['qrcode_left_px'] / 0.7), ($info['qrcode_top_px'] / 0.7), 0, 0, imagesx($q_image), imagesy($q_image), 100);
                    break;
                //开启用户头像
                case 2:
                    //判断用户头像是否存在  以及用户头像对应这个海报的存在不存在
                    if (!file_exists(MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png')) {
                        //还要做一个针对这个海报的头像大小
                        $res = $this->getSecond($uinfo['headimg'], MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png');
                        if (!$res) {
                            $message = array('code' => 1002, 'msg' => '下载用户头像失败');
                            return $this->result(1, '下载用户头像失败');
                            die();
                        } else {
                            $res = json_decode($this->editheadimg($uid, $pid), true);
                            if (is_error($res)) {
                                $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                                return $this->result(1, '修改用户头像大小失败');
                                die();
                            }
                        }
                    } else {
                        if (!file_exists(MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png')) {
                            //去做这个头像
                            $res = json_decode($this->editheadimg($uid, $pid), true);
                            if (is_error($res)) {
                                $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                                return $this->result(1, '修改用户头像大小失败');
                                die();
                            }
                        }
                    }
                    $headmg_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png';
                    $h_image = imagecreatefrompng($headmg_path);
                    imagecopymerge($y_image, $h_image, ($info['head_left_px'] / 0.7), ($info['head_top_px'] / 0.7), 0, 0, imagesx($h_image), imagesy($h_image), 100);
                    //合并头像到海报
                    break;
                //开启用户昵称
                case 3:
                    $nick_color = $this->hex2rgb($info['nick_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['nick_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['nick_left_px'] / 0.7);      //左边距
                    $top = ($info['nick_top_px'] + $info['nick_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $uinfo['nickname']);
                    break;
                //开启学习天数
                case 4:
                    $nick_color = $this->hex2rgb($info['study_day_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['study_day_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['study_day_left_px'] / 0.7);      //左边距
                    $top = ($info['study_day_top_px'] + $info['study_day_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $time);
                    break;
                //开启日期
                case 5:
                    $weekarray = array("日", "一", "二", "三", "四", "五", "六");
                    $week = "星期" . $weekarray[date("w", time())];
                    $date = date('Y/m/d', time()) . $week;
                    $nick_color = $this->hex2rgb($info['date_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['date_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['date_left_px'] / 0.7);      //左边距
                    $top = ($info['date_top_px'] + $info['date_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $date);
                    break;
            }
        }
        $res = imagepng($y_image, MODULE_ROOT . '/images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png');
        $path = MODULE_URL . 'images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png';
        if ($res) {
            return $this->result(0, '海报路径', ['path' => $path]);
        } else {
            return $this->result(1, '生成海报图片失败');
        }
    }

    public function doPagelessonposternew()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户ID错误');
        }
        $lessonid = $_GPC['lessonid'];
        $sonid = $_GPC['sonid'];
        $has_lesson = pdo_get($this->t_lesson, ['id' => $lessonid, 'status' => 1]);
        $has_son = pdo_get($this->t_son, ['id' => $sonid, 'status' => 1]);
        if (empty($has_lesson) || empty($has_son)) {
            return $this->result(1, '课程章节不存在');
        }
        //获取所有可用的海报设计  从中所及抽取一张
        $sql = 'select * from ' . tablename($this->t_poster) . " where weid = :weid and status = :status";
        $params = [':weid' => $_W['uniacid'], ':status' => 1];
        $poster_list = pdo_fetchall($sql, $params);
        if (empty($poster_list)) {
            return $this->result(1, '没有可用的海报');
        }
        $info = $poster_list[array_rand($poster_list)];
        $info['option'] = unserialize($info['option']);
        $uinfo = pdo_get($this->t_user, array('id' => $uid));
        /*创建相应的文件夹*/
        $pid = $info['id'];
        $qrcode_path = MODULE_ROOT . '/images/Poster/qrcode/';
        if (!is_dir($qrcode_path)) {
            mkdir($qrcode_path, 0777, true);
        }
        $headerimg_natival = MODULE_ROOT . '/images/Poster/headerimg/header/';
        if (!is_dir($headerimg_natival)) {
            mkdir($headerimg_natival, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_header_path = MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/';
        if (!is_dir($has_header_path)) {
            mkdir($has_header_path, 0777, true);
        }
        $has_poster_path = MODULE_ROOT . '/images/Poster/poster/' . $pid . '/';
        if (!is_dir($has_poster_path)) {
            mkdir($has_poster_path, 0777, true);
        }
        $has_lessonqrcode_path = MODULE_ROOT . '/images/Poster/lesson/qrcode/';
        if (!is_dir($has_lessonqrcode_path)) {
            mkdir($has_lessonqrcode_path, 0777, true);
        }
        $has_lessonqrcodeposter_path = MODULE_ROOT . '/images/Poster/lesson/qrcodeposter/' . $pid . '/';
        if (!is_dir($has_lessonqrcodeposter_path)) {
            mkdir($has_lessonqrcodeposter_path, 0777, true);
        }
        /*创建文件夹结束*/
        /*判断用户这个海报是否存在开始*/
        //如果不判断是否存在 一个用户值会存在一张  如果判断的话需要将海报对应日期  ？？？？？？
        /*$poster_img = MODULE_ROOT.'/images/Poster/poster/'.$pid.'/'.$uid.'_'.$pid.'.png';
        //判断示例图片是否存在
        if(file_exists($poster_img)){
            //已经生成过预览图  直接返回图片路径
            echo 123;die();
        }*/
        /*判断用户这个海报是否存在结束*/
        //继续整理需要的信息  1.获取用户总签到天数 当做学习天数
        $time = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_signin) . " where weid = :weid and uid = :uid ", array(':weid' => $_W['uniacid'], ':uid' => $uid));
        //生成海报
        $y_image = imagecreatetruecolor(616, 846);
        $bgimg_path = $_W['attachurl'] . $info['bgimg'];
        //        return $this->result(1,'路径',['path'=>$bgimg_path]);
        $b_image = imagecreatefrompng($bgimg_path);
        imagecopymerge($y_image, $b_image, 0, 0, 0, 0, imagesx($b_image), imagesy($b_image), 100);
        $font = MODULE_ROOT . '/images/simhei.ttf';
        foreach ($info['option'] as $k => $v) {
            switch ($v) {
                //开启二维码
                case 1:
                    //判断用户二维码是否存在  以及用户二维码对应这个海报的存在不存在
                    if (!file_exists(MODULE_ROOT . '/images/Poster/lesson/qrcode/' . $uid . '_' . $lessonid . '.jpg')) {
                        //用户二维码不存在，则对应海报的二维码肯定也不存在
//                        $res = json_decode($this->mkqrcode1($uid,$lessonid,$sonid),true);
                        $appid = $_W['account']['key'];
                        $secret = $_W['account']['secret'];
                        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
                        $access_token = json_decode($this->curl_get($url), true)['access_token'];
                        // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
                        $data = array();
                        $data['page'] = 'pages/selected/selected';//路径
                        // $data['path'] = '';//路径
                        // $data['scene'] = 'uid='.$uid.'&lid='.$lessonid.'&page=SD';//场景参数
                        $data['scene'] = 'u=' . $uid . '&l=' . $lessonid . '&p=SD&s=' . $sonid;
                        $data = json_encode($data);
                        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
                        $da = $this->get_http_array($url, $data);
                        $file_put_result = file_put_contents(MODULE_ROOT . '/images/Poster/lesson/qrcode/' . $uid . '_' . $lessonid . '.jpg', $da);
                        if (is_error($file_put_result)) {
                            return $this->result(1, '未生成二维码');
                        }
                        /* if($res['code'] == 200){

                        }else{
                            return $this->result(1,$res['msg']);
                        }*/
                        if (is_error($file_put_result)) {
                            $message = ['code' => 1001, 'msg' => '写入二维码信息失败'];
                            return $this->result(1, '写入二维码信息失败');
                            die();
                        } else {
                            //去制作对应还包的二维码图片
                            $res = json_decode($this->editqrcode1($uid, $pid, $lessonid), true);
                            if ($res['code'] != 200) {
                                $message = ['code' => 1002, 'msg' => '合并二维码失败'];
                                return $this->result(1, '合并二维码失败', $message);
                                die();
                            }
                        }
                    } else {
                        if (!file_exists(MODULE_ROOT . '/images/Poster/lesson/qrcodeposter/' . $pid . '/' . $uid . '_' . $lessonid . '.png')) {
                            //去做这个二维码
                            $res = json_decode($this->editqrcode1($uid, $pid, $lessonid), true);
                            if ($res['code'] != 200) {
                                $message = ['code' => 1002, 'msg' => '修改二维码大小失败'];
                                return $this->result(1, '修改二维码大小失败', $message);
                                die();
                            }
                        }
                    }
                    //制作成功 合并二维码与画布
                    $qrcode_path = MODULE_ROOT . '/images/Poster/lesson/qrcodeposter/' . $pid . '/' . $uid . '_' . $lessonid . '.png';
                    $q_image = imagecreatefrompng($qrcode_path);
                    imagecopymerge($y_image, $q_image, ($info['qrcode_left_px'] / 0.7), ($info['qrcode_top_px'] / 0.7), 0, 0, imagesx($q_image), imagesy($q_image), 100);
                    break;
                //开启用户头像
                case 2:
                    //判断用户头像是否存在  以及用户头像对应这个海报的存在不存在
                    if (!file_exists(MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png')) {
                        //还要做一个针对这个海报的头像大小
                        $res = $this->getSecond($uinfo['headimg'], MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png');
                        if (!$res) {
                            $message = array('code' => 1002, 'msg' => '下载用户头像失败');
                            return $this->result(1, '下载用户头像失败');
                            die();
                        } else {
                            $res = json_decode($this->editheadimg($uid, $pid), true);
                            if (is_error($res)) {
                                $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                                return $this->result(1, '修改用户头像大小失败');
                                die();
                            }
                        }
                    } else {
                        if (!file_exists(MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png')) {
                            //去做这个头像
                            $res = json_decode($this->editheadimg($uid, $pid), true);
                            if (is_error($res)) {
                                $message = ['code' => 1003, 'msg' => '修改用户头像大小失败'];
                                return $this->result(1, '修改用户头像大小失败');
                                die();
                            }
                        }
                    }
                    $headmg_path = MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png';
                    $h_image = imagecreatefrompng($headmg_path);
                    imagecopymerge($y_image, $h_image, ($info['head_left_px'] / 0.7), ($info['head_top_px'] / 0.7), 0, 0, imagesx($h_image), imagesy($h_image), 100);
                    //合并头像到海报
                    break;
                //开启用户昵称
                case 3:
                    $nick_color = $this->hex2rgb($info['nick_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['nick_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['nick_left_px'] / 0.7);      //左边距
                    $top = ($info['nick_top_px'] + $info['nick_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $uinfo['nickname']);
                    break;
                //开启学习天数
                case 4:
                    $nick_color = $this->hex2rgb($info['study_day_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['study_day_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['study_day_left_px'] / 0.7);      //左边距
                    $top = ($info['study_day_top_px'] + $info['study_day_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $time);
                    break;
                //开启日期
                case 5:
                    $weekarray = array("日", "一", "二", "三", "四", "五", "六");
                    $week = "星期" . $weekarray[date("w", time())];
                    $date = date('Y/m/d', time()) . $week;
                    $nick_color = $this->hex2rgb($info['date_font_color']);
                    $black = imagecolorallocate($y_image, $nick_color['r'], $nick_color['g'], $nick_color['b']);//字体颜色 RGB
                    $fontSize = ($info['date_size_px'] / 0.7);   //字体大小
                    $circleSize = 0; //旋转角度
                    $left = ($info['date_left_px'] / 0.7);      //左边距
                    $top = ($info['date_top_px'] + $info['date_size_px']) / 0.7;       //顶边距
                    imagefttext($y_image, $fontSize, $circleSize, $left, $top, $black, $font, $date);
                    break;
            }
        }
        $res = imagepng($y_image, MODULE_ROOT . '/images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png');
        $path = MODULE_URL . 'images/Poster/poster/' . $pid . '/' . $uid . '_' . $pid . '.png';
        if ($res) {
            return $this->result(0, '海报路径', ['path' => $path]);
        } else {
            return $this->result(1, '生成海报图片失败');
        }
    }

    /************配合成成海报的函数**************/
    public function mkqrcode($uid)
    {
        $account_api = WeAccount::create();
        //还要做一个针对这个海报的头像大小
        $response = $account_api->getCodeLimit('pages/selected/selected?u=' . $uid, 430, array(
            'auto_color' => false,
            'line_color' => array(
                'r' => '#ABABAB',
                'g' => '#ABABAC',
                'b' => '#ABABAD',
            ),
            'is_hyaline' => false
        ));
        if (is_error($response)) {
            $message = ['code' => $response['errno'], 'msg' => $response['message']];
        } else {
            $message = ['code' => 200, 'content' => $response['content']];
        }
        return json_encode($message);
    }

    public function mkqrcodes($uid)
    {
        global $_W, $_GPC;
        /*$account_api = WeAccount::create();
        //还要做一个针对这个海报的头像大小
        $response = $account_api->getCodeLimit('pages/home/home?u='.$uid, 430, array(
            'auto_color' => false,
            'line_color' => array(
                'r' => '#ABABAB',
                'g' => '#ABABAC',
                'b' => '#ABABAD',
            ),
            'is_hyaline' => false
        ));
        return json_encode($response);*/
        /*if(is_error($response)){
            $message = ['code'=>$response['errno'],'msg'=>$response['message']];
        }else{
            $message = ['code'=>200,'content'=>$response['content']];
        }*/
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $access_token = json_decode($this->curl_get($url), true)['access_token'];
        // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
        $data = array();
        $data['page'] = 'pages/home/home';//路径
        // $data['path'] = '';//路径
        // $data['scene'] = 'uid='.$uid.'&lid='.$lessonid.'&page=SD';//场景参数
        $data['scene'] = 'u=' . $uid;
        $data = json_encode($data);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $da = $this->get_http_array($url, $data);
        return json_encode($da);
    }

    public function mkqrcode1($uid, $lessonid, $sonid)
    {
        global $_W, $_GPC;
        /*$account_api = WeAccount::create();
        //还要做一个针对这个海报的头像大小
        $response = $account_api->getCodeLimit('pages/selected/selected?u='.$uid.'&p=SD&l='.$lessonid.'&s='.$sonid, 430, array(
            'auto_color' => false,
            'line_color' => array(
                'r' => '#ABABAB',
                'g' => '#ABABAC',
                'b' => '#ABABAD',
            ),
            'is_hyaline' => false
        ));

        return json_encode($response);*/
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $access_token = json_decode($this->curl_get($url), true)['access_token'];
        // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
        $data = array();
        $data['page'] = 'pages/selected/selected';//路径
        // $data['path'] = '';//路径
        // $data['scene'] = 'uid='.$uid.'&lid='.$lessonid.'&page=SD';//场景参数
        $data['scene'] = 'u=' . $uid . '&l=' . $lessonid . '&p=SD&s=' . $sonid;
        $data = json_encode($data);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $da = $this->get_http_array($url, $data);
        return json_encode($da);
    }

    //制作二维码对应海报的图片
    public function editqrcode($uid, $pid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/Qrcode/qrcode_' . $uid . '.jpg', MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

    public function editqrcodes($uid, $pid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/qrcode/qrcode/qrcode_' . $uid . '.jpg', MODULE_ROOT . '/images/Poster/qrcode/qrcodeposter/' . $pid . '/' . $uid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

    public function editqrcode1($uid, $pid, $lessonid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['qrcode_width_px'] = $info['qrcode_width_px'] / 0.7;
        $info['qrcode_height_px'] = $info['qrcode_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/lesson/qrcode/' . $uid . '_' . $lessonid . '.jpg', MODULE_ROOT . '/images/Poster/lesson/qrcodeposter/' . $pid . '/' . $uid . '_' . $lessonid . '.png', $info['qrcode_width_px'], $info['qrcode_height_px']);
        if ($res) {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        } else {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        }
        return json_encode($message);
    }

    //下载用户头像到服务器
    public function getSecond($url, $new_file)
    {
        $header = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
            $img_content = $imgBase64Code;//图片内容
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
                $type = $result[2];//得到图片类型png?jpg?gif?
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    //制作用户头像对应海报的图片
    public function editheadimg($uid, $pid)
    {
        $info = pdo_get($this->t_poster, ['id' => $pid]);
        $info['head_width_px'] = $info['head_width_px'] / 0.7;
        $info['head_height_px'] = $info['head_height_px'] / 0.7;
        $res = $this->tailoring(MODULE_ROOT . '/images/Poster/headerimg/header/' . $uid . '.png', MODULE_ROOT . '/images/Poster/headerimg/headerposter/' . $pid . '/' . $uid . '.png', $info['head_width_px'], $info['head_height_px']);
        if (is_error($res)) {
            $message = ['code' => 404, 'msg' => '图片生成失败'];
        } else {
            $message = ['code' => 200, 'msg' => '图片生成成功'];
        }
        return json_encode($message);
        exit;
    }

    //修改图片大小
    public function tailoring($img_path, $new_img_path, $width, $height)
    {
        $img_info = @getimagesize($img_path);
        if (!$img_info || $width < 1 || $height < 1 || empty($new_img_path)) {
            return false;
        }
        if (strpos($img_info['mime'], 'jpeg') !== false) {
            $pic_obj = imagecreatefromjpeg($img_path);
        } else if (strpos($img_info['mime'], 'gif') !== false) {
            $pic_obj = imagecreatefromgif($img_path);
        } else if (strpos($img_info['mime'], 'png') !== false) {
            $pic_obj = imagecreatefrompng($img_path);
        } else {
            return false;
        }
        $pic_width = imagesx($pic_obj);
        $pic_height = imagesy($pic_obj);
        if (function_exists("imagecopyresampled")) {
            $new_img = imagecreatetruecolor($width, $height);
            imagecopyresampled($new_img, $pic_obj, 0, 0, 0, 0, $width, $height, $pic_width, $pic_height);
        } else {
            $new_img = imagecreate($width, $height);
            imagecopyresized($new_img, $pic_obj, 0, 0, 0, 0, $width, $height, $pic_width, $pic_height);
        }
        if (preg_match('~.([^.]+)$~', $new_img_path, $match)) {
            $new_type = strtolower($match[1]);
            switch ($new_type) {
                case 'jpg':
                    imagejpeg($new_img, $new_img_path);
                    break;
                case 'gif':
                    imagegif($new_img, $new_img_path);
                    break;
                case 'png':
                    imagepng($new_img, $new_img_path);
                    break;
                default:
                    imagejpeg($new_img, $new_img_path);
            }
        } else {
            imagejpeg($new_img, $new_img_path);
        }
        imagedestroy($pic_obj);
        imagedestroy($new_img);
        return true;
    }

    //16进制颜色转rgb
    public function hex2rgb($hexColor)
    {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }
    /************配合成成海报的函数**************/
    /***3.0辅助函数开始****/
    /***3.0辅助函数开始****/
    //获取opdnid
    public function getopenidnew($code)
    {
        global $_W, $_GPC;
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $str = $this->httpGet($api);
        return $str;
    }

    //购买函数
    public function userpay($uid, $lessonid, $type = 1, $groupid = 0, $usercardid = 0)
    {
        /*
         *type = 1 原价购买 2 开团支付 3 参团支付 4 使用兑课券支付
         *  */
        global $_W;
        $userinfo = pdo_get($this->t_user, array('id' => $uid));
        $lessoninfo = pdo_get($this->t_lesson, array('id' => $lessonid));
        $config = $this->module['config'];
        //判断有没有购买过这个课程的订单
        $is_pay = pdo_get($this->t_order, array('userid' => $userinfo['id'], 'dataid' => $lessoninfo['id'], 'weid' => $_W['uniacid'], 'type' => 1));
        /*if($config['pay_status'] == 0){
            return $this->result(1,'暂未开启购买功能',array('error'=>0));exit;
        }*/
        $appid = $_W['account']['key'];
        $appsecret = $_W['account']['secret'];
        if ($_W['account']['level'] < 4) {
            $uniacid = $_W['oauth_account']['acid'];
            $appid = $_W['oauth_account']['key'];
            $appsecret = $_W['oauth_account']['secret'];
        }
        $payset = array('appid' => $appid, 'appsecret' => $appsecret, 'mchid' => $config['mchid'], 'shkey' => $config['pay_secret']);
        /*if(!empty($_GPC['lessonid'])){

            $info = pdo_get('goouc_class_lesson',array('weid'=>$_W['uniacid'],'id'=>$_GPC['lessonid']));

            $is_pay = pdo_get("goouc_os_order",array('userid'=>$userinfo['id'],'dataid'=>$info['id'],'weid'=>$_W['uniacid'],'type'=>1));
        }elseif(!empty($_GPC['sonid'])){

            $info = pdo_get('goouc_class_son',array('weid'=>$_W['uniacid'],'id'=>$_GPC['sonid']));

            $is_pay = pdo_get("goouc_os_order",array('userid'=>$userinfo['id'],'dataid'=>$info['id'],'weid'=>$_W['uniacid'],'type'=>2));

            $is_pay_lesson_son = pdo_get('goouc_os_order',array('userid'=>$userinfo['id'],'dataid'=>$info['lessonid'],'weid'=>$_W['uniacid'],'type'=>1));
            if($is_pay['order_status'] == 1   || $is_pay_lesson_son['order_status'] == 1 ){
                return $this->result(0,'你已购买过章节或文章，请勿重复购买',array('error'=>6));
            }
        }*/
        if (empty($lessoninfo) || $lessoninfo['status'] == 0) {
            $message = ['code' => 3003, 'msg' => '要购买的课程或章节不存在'];
            return $message;
        }
        $order = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $uid . $lessonid;
        if ($type == 2 || $type == 3) {
            $money = (int)(floatval($lessoninfo['old_money']) * 100);
            $data['true_money'] = $lessoninfo['old_money'];
            $data['groupid'] = $groupid;
        } elseif ($type == 4) {
            //查出兑课券抵扣金额
            $cardinfo = pdo_fetch("select * from " . tablename($this->t_user_exchange) . " ue JOIN " . tablename($this->t_cardinfo) . " c ON ue.cid = c.id where ue.id = :id ", array(':id' => $usercardid));
            $money = (int)(floatval($lessoninfo['pay_money']) * 100) - (int)(floatval($cardinfo['price']) * 100);
            $data['true_money'] = $lessoninfo['pay_money'] - $cardinfo['price'];
            $data['usercardid'] = $usercardid;
        } else {
            $money = (int)(floatval($lessoninfo['pay_money']) * 100);
            $data['true_money'] = $lessoninfo['pay_money'];
        }
        $data['weid'] = $_W['uniacid'];
        /*if(!empty($_GPC['lessonid'])){
            $data['dataid'] = $_GPC['lessonid'];
            $data['type'] = 1;
        }elseif(!empty($_GPC['sonid'])){
            $data['dataid'] = $_GPC['sonid'];
            $data['type'] = 2;
        }*/
        $data['dataid'] = $lessonid;
        $data['type'] = $type;
        $data['openid'] = $userinfo['openid'];
        $data['userid'] = $uid;
        $data['out_trade_no'] = $order;
        $data['all_money'] = $lessoninfo['pay_money'];
        $data['order_status'] = 0;
        $data['createtime'] = time();
        $data['module'] = 2;
        $res = pdo_insert($this->t_order, $data);
        $payment_id = pdo_insertid();
        if (!$res) {
            $message = ['code' => 1001, 'msg' => '生成订单失败'];
            return $message;
        }
        $nonce_str = getNonceStr(28);
        $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
        $notify_url = $_W['siteroot'] . "/addons/goouc_class/wxresult.php";
        $dataurl = array(
            'appid' => $_W['account']['key'],
            'mch_id' => $payset['mchid'],
            'nonce_str' => $nonce_str,
            'body' => $lessoninfo['title'],
            'out_trade_no' => $order,
            'total_fee' => $money,
            'spbill_create_ip' => $spbill_create_ip,
            'notify_url' => $notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $userinfo['openid']
        );
        $sign = getSign($dataurl, $payset['shkey']);
        $dataurl['sign'] = $sign;
        $xml = arrayToXml($dataurl);
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $res = xmlToUrl($xml, $url);
        libxml_disable_entity_loader(true);
        $xmlstr = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
        $returnarr = json_decode(json_encode($xmlstr), true);
        $message = [];
        if ($returnarr['return_code'] == "SUCCESS" && $returnarr['result_code'] == "SUCCESS") {
            //var_dump($returnarr);die;
            $prepay_id = $returnarr['prepay_id'];
            //$update['transaction_sn'] = $prepay_id;
            //pdo_update($this->t_order, $update, array('id' => $payment_id, 'weid' => $_W['uniacid']));
            $data = [];
            $data = array(
                'appId' => $_W['account']['key'],
                'timeStamp' => '"' . time() . '"',
                'nonceStr' => $nonce_str,
                'package' => "prepay_id=" . $prepay_id,
                'signType' => 'MD5',
            );
            $paysign = getSign($data, $payset['shkey']);
            $data['paySign'] = $paysign;
            $message['code'] = 200;
            $message['info'] = $data;
        } else {
            $message = ['code' => 1002, 'msg' => '请求支付失败', 'data' => [$returnarr, $dataurl, $sign]];
        }
        return $message;
    }

    //get方式获取url信息
    public function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /** 2.0接口* */
    //首页以及赛选课程
    public function doPageIndex()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $aliyunVod = new AliyunVod($config['regionId'], $config['AccessKeyID'], $config['AccessKeySecret']);
        $contion = "weid = :weid AND status = 1";
        $params[':weid'] = $_W['uniacid'];
        $op = empty($_GPC['op']) ? 'city' : $_GPC['op'];
        if ($op == 'city') {
            $city = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_city') . " WHERE " . $contion, $params);
            if (empty($city)) {
                $city = pdo_getall('goouc_class_city', array('weid' => $_W['uniacid']));
            }
            if (count($city) == 1) {
                $citystatus = 1;
                $city = $city;
            } elseif (count($city) > 1) {
                $city = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_city') . " WHERE " . $contion, $params);
                $citystatus = 2;
            }
            return $this->result(0, '城市信息', array('city' => $city, 'status' => $citystatus));
        } elseif ($op == 'class') {
            $class = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_class') . " WHERE " . $contion, $params);
            return $this->result(0, '年级列表', array('class' => $class, $contion, $params));
        } elseif ($op == 'subject') {
            $classid = $_GPC['classid'];
            if (!empty($classid)) {
                $contion .= " AND id = :id";
                $params[':id'] = $classid;
                $classlist = pdo_fetch("SELECT `id`,`name`,`subjectid` FROM " . tablename('goouc_class_class') . " WHERE " . $contion, $params);
                $arr_subject = unserialize($classlist['subjectid']);
                foreach ($arr_subject as $su => $us) {
                    $subject[] = pdo_fetch("SELECT `id`,`name` FROM " . tablename("goouc_class_subject") . " WHERE id = :id", array(':id' => $us));
                }
            } else {
                $subject = pdo_getall('goouc_class_subject', array('weid' => $_W['uniacid'], 'status' => 1));
            }
            return $this->result(0, '学科列表', array('subject' => $subject, $contion, $params));
        } elseif ($op == 'teacher') {
            $cityid = $_GPC['cityid'];
            $subjectid = $_GPC['subjectid'];
            if (!empty($cityid)) {
                $contion .= " AND cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($subjectid)) {
                $contion .= " AND subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            $teacher = pdo_fetchall("SELECT `id`,`name` FROM " . tablename('goouc_class_teacher') . " WHERE " . $contion, $params);
            return $this->result(0, '老师信息', array('teacher' => $teacher, $contion, $params));
        } elseif ($op == 'semester') {
            $semester = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_semester') . " WHERE " . $contion, $params);
            return $this->result(0, '学期列表', array('semester' => $semester, $contion, $params));
        } elseif ($op == 'voidtype') {
            $voidtype = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_voidtype') . " WHERE " . $contion, $params);
            return $this->result(0, '模式列表', array('voidtype' => $voidtype, $contion, $params));
        } elseif ($op == 'year') {
            $cityid = $_GPC['cityid'];
            $classid = $_GPC['classid'];
            $subjectid = $_GPC['subjectid'];
            $teacherid = $_GPC['teacherid'];
            $semesterid = $_GPC['semesterid'];
            $voidtypeid = $_GPC['voidtypeid'];
            if (!empty($cityid)) {
                $contion .= " AND cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($classid)) {
                $contion .= " AND classid LIKE '%\"" . $classid . "\"%'";
            }
            if (!empty($subjectid)) {
                $contion .= " AND subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            if (!empty($teacherid)) {
                $contion .= " AND teacherid = :teacherid";
                $params[':teacherid'] = $teacherid;
            }
            if (!empty($semesterid)) {
                $contion .= " AND semesterid = :semesterid";
                $params[':semesterid'] = $semesterid;
            }
            if (!empty($voidtypeid)) {
                $contion .= " AND voidtypeid = :voidtypeid";
                $params[':voidtypeid'] = $voidtypeid;
            }
            $year_arr = pdo_fetchall("SELECT `yearid` FROM " . tablename('goouc_class_lesson') . " WHERE " . $contion . " GROUP BY `yearid`", $params);
            $year = array();
            foreach ($year_arr as $k => $v) {
                $year[$k]['name'] = $v['yearid'];
                $year[$k]['id'] = $v['yearid'];
            }
            return $this->result(0, '年份列表', array('year' => $year, $contion, $params));
        } elseif ($op == 'lesson') {
            $cityid = $_GPC['cityid'];
            $classid = $_GPC['classid'];
            $subjectid = $_GPC['subjectid'];
            $teacherid = $_GPC['teacherid'];
            $semesterid = $_GPC['semesterid'];
            $voidtypeid = $_GPC['voidtypeid'];
            $yearid = $_GPC['yearid'];
            if (!empty($cityid)) {
                $contion .= " AND cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($classid)) {
                $contion .= " AND classid LIKE '%\"" . $classid . "\"%'";
            }
            if (!empty($subjectid)) {
                $contion .= " AND subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            if (!empty($teacherid)) {
                $contion .= " AND teacherid = :teacherid";
                $params[':teacherid'] = $teacherid;
            }
            if (!empty($semesterid)) {
                $contion .= " AND semesterid = :semesterid";
                $params[':semesterid'] = $semesterid;
            }
            if (!empty($voidtypeid)) {
                $contion .= " AND voidtypeid = :voidtypeid";
                $params[':voidtypeid'] = $voidtypeid;
            }
            if (!empty($yearid)) {
                $contion .= " AND yearid = :yearid";
                $params[':yearid'] = $yearid;
            }
            $pageindex = max(1, intval($_GPC['page']));
            $psize = 4;
            $contion .= ' AND semesterid != 0 AND  voidtypeid != 0 AND teacherid != 0 AND subjectid != 0 AND cityid != 0';
            $lesson = pdo_fetchall("SELECT `id`,`title` FROM " . tablename('goouc_class_lesson') . " WHERE " . $contion . " ORDER BY `order` DESC LIMIT " . ($pageindex - 1) * $psize . ',' . $psize, $params);
            foreach ($lesson as $k => $v) {
                $lesson[$k]['image'] = $_W['attachurl'] . $v['image'];
                $lesson[$k]['son'] = pdo_fetchall("SELECT `id`,`title`,`image`,`key`,`num`,`xnum`,`vediotime` FROM " . tablename("goouc_class_son") . " WHERE lessonid = :lessonid AND weid = :weid AND status = 1 ORDER BY `orders` DESC", array(':lessonid' => $v['id'], ':weid' => $_W['uniacid']));
                $lesson[$k]['sonnum'] = count($lesson[$k]['son']);
                foreach ($lesson[$k]['son'] as $kk => $vv) {
                    $lesson[$k]['son'][$kk]['num'] = $vv['num'] + $vv['xnum'];
                    if (!empty($lesson[$k]['son'][$kk]['image'])) {
                        $lesson[$k]['son'][$kk]['image'] = $_W['attachurl'] . $vv['image'];
                    } elseif (empty($lesson[$k]['son'][$kk]['coverurl'])) {
                        try {
                            $video = $aliyunVod->getPlayInfo($vv['key']);
                            $lesson[$k]['son'][$kk]['coverurl'] = $video->VideoBase->CoverURL;
                            pdo_update('goouc_class_son', array('coverurl' => $video->VideoBase->CoverURL), array('weid' => $_W['uniacid'], 'id' => $vv['id']));
                        } catch (Exception $e) {
                            unset($lesson[$k]['son'][$kk]);
                        }
                    }
                    //判断表中有没有视频时长 封面图片的信息
                    if ($vv['vediotime'] == '0.00') {
                        try {
                            $video = $aliyunVod->getPlayInfo($vv['key']);
                            $data['vediotime'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                            $lesson[$k]['son'][$kk]['vediotime'] = $data['vediotime'];
                            //更新数据表
                            pdo_update('goouc_class_son', $data, array('weid' => $_W['uniacid'], 'id' => $vv['id']));
                        } catch (Exception $e) {
                            unset($lesson[$k]['son'][$kk]);
                        }
                    }
                }
            }
            $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename("goouc_class_lesson") . " WHERE " . $contion, $params);
            $page = ceil($total / $psize);
            return $this->result(0, '数据列表', array('lesson' => $lesson, 'page' => $page, $contion, $params));
        } elseif ($op == 'classtype') {
            $classtype = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_classtype') . " WHERE " . $contion, $params);
            return $this->result(0, '模式列表', array('voidtype' => $classtype));
        }
    }

    //轮播图
    public function doPageBanner()
    {
        global $_W, $_GPC;
        $classid = $_GPC['classid'];
        $banner = pdo_getall('goouc_class_banner', array('weid' => $_W['uniacid'], 'status' => 1, 'position' => 1, 'classid' => $classid));
        if (empty($banner)) {
            $banner = pdo_getall('goouc_class_banner', array('weid' => $_W['uniacid'], 'status' => 1, 'position' => 1));
        }
        foreach ($banner as $k => $v) {
            $banner[$k]['image'] = $_W['attachurl'] . $v['image'];
        }
        return $this->result(0, '首页轮播图', array('banner' => $banner));
    }

    //用户详情 以及配置信息
    public function doPageUinfo()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $userinfo = pdo_get('goouc_class_user', array('id' => $uid, 'weid' => $_W['uniacid']), array('id', 'nickname', 'name', 'phone', 'headimg', 'card', 'sex', 'city1', 'city2', 'school', 'classid'));
        $userinfo['nickname'] = json_decode($userinfo['nickname']);
        $config = $this->module['config'];
        $sharset = array('nstatus' => $config['nstatus'], 'nnum' => $config['nnum'], 'lstatus' => $config['lstatus'], 'lnum' => $config['lnum'], 'sstatus' => $config['sstatus'], 'snumber' => $config['snumber'], 'snum' => $config['snum'], 'pay_status' => $config['pay_status']);
        $sharetitle = pdo_get('goouc_class_shartitle', array('weid' => $_W['uniacid']));
        return $this->result(0, '用户详情', array('userinfo' => $userinfo, 'sharset' => $sharset, 'sharetitle' => $sharetitle));
    }

    //城市报名信息
    public function doPageCityinfo()
    {
        global $_W, $_GPC;
        $citylist = pdo_getall('goouc_class_city', array('weid' => $_W['uniacid']));
        foreach ($citylist as $k => $v) {
            $citylist[$k]['image'] = $_W['attachurl'] . $v['image'];
        }
        return $this->result(0, '城市接口数据', array('citylist' => $citylist));
    }

    //核心  视频列表页内容
    public function doPageInfo()
    {
        global $_W, $_GPC;
        include_once MODULE_ROOT . "/inc/common/AliyunVod.php";
        $config = $this->module['config'];
        $aliyunVod = new AliyunVod($config['regionId'], $config['AccessKeyID'], $config['AccessKeySecret']);
        $lessonid = intval($_GPC['lessonid']);
        if (!empty($lessonid)) {
            $uid = intval($_GPC['uid']);
            $lessoninfo = pdo_get('goouc_class_lesson', array('weid' => $_W['uniacid'], 'id' => $lessonid));
            $sonlist = pdo_fetchall("SELECT * FROM " . tablename("goouc_class_son") . " WHERE lessonid = :lessonid AND weid = :weid AND status=1 ORDER BY `orders` ASC", array(':lessonid' => $lessonid, ':weid' => $_W['uniacid']));
            // 章节价格与课程价格无关
            // if($lessoninfo['pay_money'] == '0.00' || $config['pay_status'] == 0){
            if ($config['pay_status'] == 0) {

                foreach ($sonlist as $k => $v) {
                    $sonlist[$k]['num'] = $sonlist[$k]['num'] + $sonlist[$k]['xnum'];
                    if (!empty($v['image'])) {
                        $sonlist[$k]['image'] = $_W['attachurl'] . $v['image'];
                    }
                    $video = $aliyunVod->getPlayInfo($v['key']);
                    $sonlist[$k]['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                    $sonlist[$k]['img'] = $video->VideoBase->CoverURL;
                    if ($v['type'] == 0) {
                        $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                        $sonlist[$k]['lookstatus'] = 1;
                    } elseif ($v['type'] == 1) {
                        $usecard = pdo_get('goouc_class_usercard', array('uid' => $uid, 'sonid' => $v['id'], 'weid' => $_W['uniacid']));
                        if ($usecard) {
                            $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                            $sonlist[$k]['lookstatus'] = 1;
                        } else {
                            $sonlist[$k]['lookstatus'] = 2;//需要使用相应张数的听课券
                        }
                    }
                    $sonlist[$k]['video'] = $video;
                }
            } else {
                // 先判断有没有购买过课程
                $pay_lesson = pdo_get('goouc_os_order', array('weid' => $_W['uniacid'], 'dataid' => $lessonid, 'type' => 1, 'module' => 2, 'userid' => $uid, 'order_status' => 1));
                if ($pay_lesson) {
                    // 购买过课程  全部免费看
                    foreach ($sonlist as $k => $v) {
                        $sonlist[$k]['num'] = $sonlist[$k]['num'] + $sonlist[$k]['xnum'];
                        if (!empty($v['image'])) {
                            $sonlist[$k]['image'] = $_W['attachurl'] . $v['image'];
                        }
                        $video = $aliyunVod->getPlayInfo($v['key']);
                        $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                        $sonlist[$k]['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                        $sonlist[$k]['img'] = $video->VideoBase->CoverURL;
                        $sonlist[$k]['lookstatus'] = 1;
                    }
                } else {

                    foreach ($sonlist as $k => $v) {
                        $sonlist[$k]['num'] = $sonlist[$k]['num'] + $sonlist[$k]['xnum'];
                        if (!empty($v['image'])) {
                            $sonlist[$k]['image'] = $_W['attachurl'] . $v['image'];
                        }
                        $video = $aliyunVod->getPlayInfo($v['key']);
                        $sonlist[$k]['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                        $sonlist[$k]['img'] = $video->VideoBase->CoverURL;
                        if ($v['pay_money'] != '0.00' && $v['type'] == 1) {
                            //既可以使用听课券 又可以进行购买观看
                            $usecard = pdo_get('goouc_class_usercard', array('uid' => $uid, 'sonid' => $v['id'], 'weid' => $_W['uniacid']));
                            $son_ispay = pdo_get('goouc_os_order', array('weid' => $_W['uniacid'], 'userid' => $uid, 'type' => 2, 'module' => 2, 'dataid' => $v['id'], 'order_status' => 1));
                            if ($usecard || $son_ispay) {
                                //可以观看
                                $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                                $sonlist[$k]['lookstatus'] = 1;
                            } else {
                                //提示用户是购买还是使用听课券观看
                                $sonlist[$k]['lookstatus'] = 4;//用户既可以购买  也可是用听课券
                            }
                        } else {
                            // 判断一下是否设置了价格 或 使用听课券
                            if ($v['pay_money'] == '0.00') {
                                if ($v['type'] == 1) {
                                    $usecard = pdo_get('goouc_class_usercard', array('uid' => $uid, 'sonid' => $v['id'], 'weid' => $_W['uniacid']));
                                    if ($usecard) {
                                        $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                                        $sonlist[$k]['lookstatus'] = 1;
                                    } else {
                                        $sonlist[$k]['lookstatus'] = 2;//课程只能使用听课券看
                                    }
                                } else {
                                    $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                                    $sonlist[$k]['lookstatus'] = 1;
                                }
                            } elseif ($v['type'] == 0) {
                                if ($v['pay_money'] != '0.00') {
                                    $son_ispay = pdo_get('goouc_os_order', array('weid' => $_W['uniacid'], 'userid' => $uid, 'type' => 2, 'module' => 2, 'dataid' => $v['id'], 'order_status' => 1));
                                    if ($son_ispay) {
                                        $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                                        $sonlist[$k]['lookstatus'] = 1;
                                    } else {
                                        $sonlist[$k]['lookstatus'] = 3;//用户需要去购买
                                    }
                                } else {
                                    $sonlist[$k]['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
                                    $sonlist[$k]['lookstatus'] = 1;
                                }
                            }
                            /*//既没有设置价格  又不用是用听课券  可以直接看
                            if($v['pay_money'] == '0.00' && $v['type'] == 0){

                            }*/
                        }
                    }
                }
            }
            $lesson = pdo_fetch("SELECT l.id,l.title,s.name FROM " . tablename('goouc_class_lesson') . "as l JOIN " . tablename('goouc_class_subject') . "as s ON l.subjectid = s.id WHERE l.id = :id AND l.weid = :weid", array(':id' => $lessonid, ':weid' => $_W['uniacid']));
            return $this->result(0, '详情页数据', array($sonlist, $lesson));
        }
    }

    // 获取播放地址
    public function doPageGeturl()
    {
        global $_W, $_GPC;
        $lessonid = $_GPC['lessonid'];
        $sonid = $_GPC['sonid'];
        $soninfo = pdo_get('goouc_class_son', array('weid' => $_W['uniacid'], 'id' => $sonid, 'status' => 1));
        if (empty($soninfo)) {
            return $this->result(1, '章节不存');
        }
        $config = $this->module['config'];
        $aliyunVod = new AliyunVod($config['regionId'], $config['AccessKeyID'], $config['AccessKeySecret']);
        $video = $aliyunVod->getPlayInfo($soninfo['key']);
        $soninfo['url'] = $video->PlayInfoList->PlayInfo[0]->PlayURL;
        $soninfo['time'] = $video->PlayInfoList->PlayInfo[0]->Duration;
        $soninfo['img'] = $video->VideoBase->CoverURL;
        $soninfo['lookstatus'] = 1;
        return $this->result(0, '更新一下列表记录', array('soninfo' => $soninfo));
    }

    // 修改观看次数
    public function doPageLooknum()
    {
        global $_W, $_GPC;
        $sonid = $_GPC['sonid'];
        $old = pdo_query("update " . tablename('goouc_class_son') . " set num = num + 1  where id=:id", array(":id" => $sonid));
    }

    public function doPagePhonecode()
    {
        global $_W, $_GPC;
        $phone = $_GPC['phonenum'];
        $config = $this->module['config'];
        $phoneset = array('accessKeyId' => $config['accessKeyId'], 'accessKeySecret' => $config['accessKeySecret'], 'SignName' => $config['SignName'], 'TemplateCode' => $config['TemplateCode']);
        $obj = new send();
        $code = random(4, true);
        $res = $obj->sendcode($phone, $code, $phoneset);
        $res = json_decode(json_encode($res), true);
        if ($res['Code'] == 'OK') {
            $data['phone'] = $phone;
            $data['code'] = $code;
            $data['createtime'] = time();
            $data['weid'] = $_W['uniacid'];
            $result = pdo_insert('goouc_class_phonecode', $data);
        } elseif ($res['Code'] == "isv.BUSINESS_LIMIT_CONTROL") {
            return $this->result(0, '发送过于频繁', '发送过于频繁');
        }
    }

    public function Checkcode($uid, $code, $phone)
    {
        global $_W, $_GPC;
        $userinfo = pdo_fetch("SELECT * FROM " . tablename('goouc_class_user') . " WHERE id = :id AND weid = :weid", array(':id' => $uid, ':weid' => $_W['uniacid']));
        if ($userinfo['status'] == 1) {

            $list = pdo_fetch("SELECT `code`,`createtime` FROM " . tablename('goouc_class_phonecode') . " WHERE phone = :phone AND weid = :weid ORDER BY `createtime` DESC ", array(':phone' => $phone, ':weid' => $_W['uniacid']));
            if ($code != $list['code']) {
                return 0;
            } else {
                $time = time() - $list['createtime'];
                if ($time > 300) {
                    return 2;
                } else {
                    return 1;
                }
            }
        } else {
            return 3;
        }
    }

    public function doPageUserinfo()
    {
        global $_W, $_GPC;
        $userid = intval($_GPC['uid']);
        $op = trim($_GPC['op']);
        $oop = $_GPC['oop'];
        if ($op == 'post') {
            if ($oop == 'edit') {
                $checkcode = $this->Checkcode($userid, $_GPC['code'], $_GPC['phone']);
                if ($checkcode == 0) {
                    return $this->result(1, '验证码错误');
                    exit;
                } elseif ($checkcode == 2) {
                    return $this->result(1, '验证码过期');
                    exit;
                } elseif ($checkcode == 3) {
                    return $this->result(1, '用户账号异常，禁止登陆');
                    exit;
                }
            }
            $has = pdo_get('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => $userid));
            if (empty($has['name']) && empty($has['phone'])) {
                $is_use_phone = pdo_get('goouc_class_user', array('weid' => $_W['uniacid'], 'phone' => $_GPC['phone']));
                if ($is_use_phone) {
                    return $this->result(1, '该手机号已被使用');
                    exit;
                }
            }
            if (empty($_GPC['name']) || empty($_GPC['sex']) || !preg_match('/^[1][3,4,5,7,8][0-9]{9}$/', $_GPC['phone']) || empty($_GPC['headimg']) || empty($_GPC['school']) || empty($_GPC['city1']) || empty($_GPC['city2'] || empty($_GPC['classid']))) {
                return $this->result(1, '请填写完整信息');
                exit;
            }
            $data['name'] = $_GPC['name'];
            $data['sex'] = intval($_GPC['sex']);
            $data['city1'] = trim($_GPC['city1']);
            $data['city2'] = trim($_GPC['city2']);
            $data['school'] = $_GPC['school'];
            $data['classid'] = $_GPC['classid'];
            $data['headimg'] = trim($_GPC['headimg']);
            $data['phone'] = trim($_GPC['phone']);
            $res = pdo_update("goouc_class_user", $data, array('id' => $userid, 'weid' => $_W['uniacid']));
            if ($res) {
                return $this->result(0, '信息保存成功', 1);
            } else {
                return $this->result(1, '修改信息失败');
            }
        }
    }

    // 排行榜
    public function doPageRanking()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $tell = $config['number'];
        $userid = intval($_GPC['uid']);
        $userinfo = pdo_fetch("SELECT `id`,`name`,`sex`,`city1`,`city2`,`school`,`headimg`,`phone` FROM " . tablename("goouc_class_user") . " WHERE id = :id AND weid = :weid", array(':id' => $userid, ':weid' => $_W['uniacid']));
        // $userinfo['looktime'] = round(pdo_get('goouc_class_userlook',array('uid'=>$userid,'date'=>date('Ymd',strtotime("last Sunday"))))['time']/60);
        $looktime = pdo_getall('goouc_class_userlookm', array('weid' => $_W['uniacid'], 'uid' => $userid), array('time'));
        $time = 0;
        foreach ($looktime as $v) {
            $time += $v['time'];
        }
        $time = ceil($time / 60);//换算成分钟
        $userinfo['looktime'] = $time;
        $list1 = load()->object('query')->from('goouc_class_user', 'u')->leftjoin('goouc_class_userlook', 'ul')->on('u.id', 'ul.uid')->where(array('u.weid' => $_W['uniacid'], 'u.status' => 1, 'ul.date' => date('Ymd', strtotime("last Sunday")), 'ul.time >' => 300))->orderby('ul.time', DESC)->groupby('ul.uid')->limit(0, 20)->getall();
        foreach ($list1 as $k => $v) {
            $list1[$k]['headimg'] = $_W['attachment'] . $v['headimg'];
            $list1[$k]['looktime'] = round($v['time'] / 60);
        }
        if (empty($userinfo['phone'])) {
            $type = 0;
        } else {
            $type = 1;
        }
        $list2 = load()->object('query')->from('goouc_class_user', 'u')->leftjoin('goouc_class_userlookm', 'ul')->on('u.id', 'ul.uid')->where(array('u.weid' => $_W['uniacid'], 'u.status' => 1, 'ul.time >' => 300, 'ul.date' => date('Ym01', strtotime(date("Y-m-d")))))->orderby('ul.time', DESC)->groupby('ul.uid')->limit(0, 20)->getall();
        foreach ($list2 as $k => $v) {
            $list2[$k]['headimg'] = $_W['attachment'] . $v['headimg'];
            $list2[$k]['looktime'] = round($v['time'] / 60);
        }
        return $this->result(0, '', array('type' => $type, 'userinfo' => $userinfo, 'list1' => $list1, 'list2' => $list2, 'tell' => $tell));
    }

    // 意见绑定手机号
    public function doPageGetphone()
    {
        global $_W, $_GPC;
        $code = $_GPC['code'];
        $info = json_decode($this->getopenid($code), true);
        $session_key = $info['session_key'];
        $encryptedData = $_GPC['encryptedData'];
        $iv = $_GPC['iv'];
        if (!empty($encryptedData) && !empty($iv)) {
            $res = $this->wxphone($session_key, $encryptedData, $iv);
            if ($res['success'] == 1) {
                return $this->result(0, '已获取到手机号', array('phoneNumber' => $res['phoneNumber']));
            } elseif ($res['success'] == 0) {
                return $this->result(0, '获取手机号失败');
            }
        }
    }

    public function wxphone($session_key, $encryptedData, $iv)
    {
        global $_W, $_GPC;
        $appid = $_W['account']['key'];
        $pc = new WXBizDataCrypt($appid, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $a = json_decode($data, true);
            $result['phoneNumber'] = $a['phoneNumber'];
            $result['success'] = 1;
        } else {
            $result['phoneNumber'] = json_decode($errCode, true);
            $result['success'] = 0;
        }
        return $result;
    }

    public function doPageDenglu()
    {
        global $_W, $_GPC;
        $code = trim($_GPC['code']);
        $nickname = $_GPC['nickname'];
        $avatar = $_GPC['avatar'];
        if (!empty($code)) {
            $info = json_decode($this->getopenid($code));
            $userinfo = pdo_fetch("SELECT `id`,`status`,`new_status` FROM " . tablename("goouc_class_user") . " WHERE openid = :openid AND weid = :weid", array(':openid' => $info->openid, ':weid' => $_W['uniacid']));
            if (empty($userinfo)) {
                $data['openid'] = $info->openid;
                $data['nickname'] = json_encode($nickname);
                $data['headimg'] = $avatar;
                $data['weid'] = $_W['uniacid'];
                $data['createtime'] = time();
                pdo_insert('goouc_class_user', $data);
                $userid = pdo_insertid();
                return $this->result(0, '老铁第一次来', array('uid' => $userid, 'first' => 1));
            } else {
                if ($userinfo['status'] == 0) {
                    return $this->result(1, '您已被禁用，暂时无法登陆小程序');
                } else {
                    if ($userinfo['new_status'] == 1) {
                        if (empty($code) || empty($nickname) || empty($avatar)) {
                            return $this->result(1, '信息不完整');
                            exit;
                        }
                        $data['openid'] = $info->openid;
                        $data['nickname'] = json_encode($nickname);
                        $data['headimg'] = $avatar;
                        $data['weid'] = $_W['uniacid'];
                        $data['new_status'] = 0;
                        $data['createtime'] = time();
                        pdo_update('goouc_class_user', $data, array('weid' => $_W['uniacid'], 'openid' => $info->openid));
                        return $this->result(0, '老铁第一次来', array('uid' => $userinfo['id'], 'first' => 1));
                    } else {
                        return $this->result(0, '来了 老铁', array('uid' => $userinfo['id'], 'first' => 0));
                    }
                }
            }
        }
    }

    public function doPageConfig()
    {
        global $_W, $_GPC;
        $a = $this->module['config'];
        $config = array(
            'nstatus' => $a['nstatus'],
            'nnum' => $a['nnum'],
            'lstatus' => $a['lstatus'],
            'lnum' => $a['lnum'],
            'sstatus' => $a['sstatus'],
            'snumber' => $a['snumber'],
            'snum' => $a['snum']
        );
        return $this->result(0, '程序配置接口', array('config' => $config));
    }

    public function doPageLoginout()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        $data['loginstatus'] = 0;
        $res = pdo_update('goouc_class_user', $data, array('id' => $uid, 'weid' => $_W['uniacid']));
        if ($res) {
            return $this->result(0, '退出成功', 1);
        } else {
            return $this->result(0, '退出失败', 0);
        }
    }

    public function doPageUploadimage()
    {
        global $_GPC, $_W;
        $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');
        $max_file_size = 2000000;
        $destination_folder = $_GPC['m'] . "/";
        if (!is_uploaded_file($_FILES["upfile"]['tmp_name'])) {
            echo "图片不存在!";
            exit;
        }
        $file = $_FILES["upfile"];
        if ($max_file_size < $file["size"]) {
            echo "文件太大!";
            exit;
        }
        if (!in_array($file["type"], $uptypes)) {
            echo "文件类型不符!" . $file["type"];
            exit;
        }
        if (!file_exists("../attachment/" . $destination_folder)) {
            mkdir("../attachment/" . $destination_folder);
        }
        $filename = $file["tmp_name"];
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo['extension'];
        $destination = "../attachment/" . $destination_folder . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;
        if (!move_uploaded_file($filename, $destination)) {
            echo "移动文件出错";
            exit;
        }
        $pinfo = pathinfo($destination);
        $fname = $pinfo['basename'];
        echo $_W['attachurl'] . $destination_folder . $fname;
    }

    public function doPageShar()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $sharset = array('nstatus' => $config['nstatus'], 'nnum' => $config['nnum'], 'lstatus' => $config['lstatus'], 'lnum' => $config['lnum'], 'sstatus' => $config['sstatus'], 'snumber' => $config['snumber'], 'snum' => $config['snum'], 'zsnum' => $config['zsnum']);
        $uid = intval($_GPC['uid']);
        $op = trim($_GPC['op']);
        if ($op == 'first') {
            $num = $sharset['nnum'];
            $userinfo = pdo_get('goouc_class_user', array('id' => $uid));
            $data['card'] = $num + $userinfo['card'];
            $res = pdo_update('goouc_class_user', $data, array('id' => $uid));
            if ($res) {
                return $this->result(0, '新用户领取听课券成功', 0);
            } else {
                return $this->result(0, '新用户领取听课券失败', 1);
            }
        } elseif ($op == 'shar') {
            $bcode = $_GPC['code'];
            $info = json_decode($this->getopenid($bcode));
            $userinfo = pdo_fetch("SELECT `id` FROM " . tablename("goouc_class_user") . " WHERE openid = :openid AND weid = :weid", array(':openid' => $info->openid, ':weid' => $_W['uniacid']));
            if (empty($userinfo)) {
                // 生成一条新用户
                $new_user = array('weid' => $_W['uniacid'], 'openid' => $info->openid, 'new_status' => 1, 'createtime' => time());
                pdo_insert('goouc_class_user', $new_user);
                $buid = pdo_insertid();
            } else {
                $buid = $userinfo['id'];
            }
            $day_has1 = pdo_get('goouc_class_usershar', array('weid' => $_W['uniacid'], 'uid' => $uid, 'buid' => $buid, 'date' => date('Ymd')));
            $day_has2 = pdo_get('goouc_class_usershar', array('weid' => $_W['uniacid'], 'uid' => $buid, 'buid' => $uid, 'date' => date('Ymd')));
            if ($day_has1 || $day_has2) {
                return $this->result(1, '两位已经得到过相应的奖励');
            } else {
                // 在分享表生成分享与被分享的关系数据
                $shar = array('weid' => $_W['uniacid'], 'uid' => $uid, 'buid' => $buid, 'date' => date('Ymd'));
                pdo_insert('goouc_class_usershar', $shar);
                //判断是否给他们加听课券
                $from_user_num = pdo_fetchcolumn("select count(*) from " . tablename('goouc_class_usershar') . " where weid=:weid AND uid=:uid AND date=:date AND buid != 0", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':date' => date('Ymd')));
                $to_user_num = pdo_fetchcolumn("select count(*) from " . tablename('goouc_class_usershar') . " where weid=:weid AND buid=:buid AND date=:date", array(':weid' => $_W['uniacid'], ':buid' => $buid, ':date' => date('Ymd')));
                //判断分享者今天分享的总共得到多少张
                if ($from_user_num * $sharset['snum'] <= 1 * $sharset['zsnum']) {
                    //给分享者添加
                    $res = pdo_query('update  ' . tablename('goouc_class_user') . ' set card = card +' . $sharset['snum'] . ' where weid=:weid AND id=:id', array(':weid' => $_W['uniacid'], ':id' => $uid));
                }
                if ($to_user_num * $sharset['snum'] <= 1 * $sharset['zsnum']) {
                    //给分享者添加
                    $res = pdo_query('update  ' . tablename('goouc_class_user') . ' set card = card +' . $sharset['snum'] . ' where weid=:weid AND id=:id', array(':weid' => $_W['uniacid'], ':id' => $buid));
                    $message = array('code' => 1, 'messs' => '获取听课券成功', 'num' => $sharset['snum']);
                    return $this->result(0, '已获得听课券', $message);
                } else {
                    $message = array('code' => 1, 'messs' => '当天获得听课券已达到上限');
                    return $this->result(1, '当天获得听课券已达到上限', $message);
                }
                // return $this->result(1,'分享加',array($from_user_num*$sharset['snum'],$sharset['zsnum'],));
            }
        } elseif ($op == 'loginin') {
            $logininfo = pdo_get('goouc_class_signin', array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01', time())));
            $data['uid'] = $uid;
            $data['weid'] = $_W['uniacid'];
            if (empty($logininfo)) {
                //该用户还没有签到过  生成一条签到记录数据
                $data['num'] = 1;
                $data['date'] = date('Ymd', time());
                $data['month'] = date('Ym01', time());
                $a = array(date('d', time()));
                $data['day'] = serialize($a);
                $res = pdo_insert('goouc_class_signin', $data);
                if ($res) {
                    // 发相应的听课券
                    if ($sharset['lstatus'] == 1) {
                        // 查询是否达到签到连续天数
                        $signinfo = pdo_get('goouc_class_signin', array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01')));
                        if ($signinfo['num'] >= $config['lday'] && $signinfo['status'] == 0) {
                            //领取连续签到奖励
                            $sharset['lnum'] = $sharset['lnum'] + $sharset['ldnum'];
                        }
                        pdo_query("UPDATE " . tablename('goouc_class_user') . " set card = card + " . $sharset['lnum'] . "  where id=:id", array(":id" => $uid));
                    }
                    return $this->result(0, '当天签到成功', array('status' => 1, 'num' => $sharset['lnum']));
                } else {
                    return $this->result(0, '当天签到失败', array('status' => 0));
                }
            } elseif ($logininfo['date'] == date('Ymd', time())) {
                return $this->result(0, '今日已签到成功 明天再来', array('status' => 3));
            } else {
                //老用户  更新签到
                $data['date'] = date('Ymd', time());
                $data['month'] = date('Ym01', time());
                if ($data['date'] - $logininfo['date'] == 1) {
                    $data['num'] = $logininfo['num'] + 1;
                } else {
                    $data['num'] = 1;
                }
                $a = unserialize($logininfo['day']);
                $a[] = date('d', time());
                $data['day'] = serialize($a);
                $res = pdo_update('goouc_class_signin', $data, array('uid' => $uid, 'weid' => $_W['uniacid']));
                if ($res) {
                    // 发相应的听课券
                    if ($sharset['lstatus'] == 1) {
                        // 查询是否达到签到连续天数
                        $signinfo = pdo_get('goouc_class_signin', array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01')));
                        if ($signinfo['num'] >= $config['lday'] && $signinfo['status'] == 0) {
                            //领取连续签到奖励
                            $sharset['lnum'] = $sharset['lnum'] + $sharset['ldnum'];
                        }
                        pdo_query("UPDATE " . tablename('goouc_class_user') . " set card = card + " . $sharset['lnum'] . "  where id=:id", array(":id" => $uid));
                    }
                    return $this->result(0, '当天签到成功', array('status' => 1, 'num' => $sharset['lnum']));
                } else {
                    return $this->result(0, '当天签到失败', array('status' => 0));
                }
            }
        } elseif ($op == 'checke') {
            //有分享举动  先发奖励
            $usershar = pdo_get('goouc_class_usershar', array('weid' => $_W['uniacid'], 'uid' => $uid, 'buid' => 0, 'date' => date('Ymd', time())));
            if (empty($usershar)) {
                $dataa['weid'] = $_W['uniacid'];
                $dataa['uid'] = $uid;
                $dataa['buid'] = 0;
                $dataa['date'] = date('Ymd', time());
                $dataa['num'] = 1;
                $dataa['cardnum'] = $sharset['snum'];
                pdo_insert('goouc_class_usershar', $dataa);
                pdo_query('update ' . tablename('goouc_class_user') . " set card = card + " . $sharset['snum'] . " where id=:id AND weid=:weid", array(':id' => $uid, ':weid' => $_W['uniacid']));
                return $this->result(0, '分享者得到听课券', array('code' => 1, 'num' => $sharset['snum']));
            } else {
                if ($usershar['num'] >= $sharset['snumber']) {
                    return $this->result(1, '上限了', array('code' => 1, 'num' => $sharset['snum']));
                    exit;
                } else {
                    //分享获取没有达到上限
                    $dataa['num'] = $usershar['num'] + 1;
                    $dataa['cardnum'] = $usershar['cardnum'] + $sharset['snum'];
                    pdo_update('goouc_class_usershar', $dataa, array('id' => $usershar['id']));
                    // 给用户加听课券
                    pdo_query('update ' . tablename('goouc_class_user') . " set card = card + " . $sharset['snum'] . " where id=:id AND weid=:weid", array(':id' => $uid, ':weid' => $_W['uniacid']));
                    return $this->result(0, '分享者得到听课券', array('code' => 1, 'num' => $sharset['snum']));
                }
            }
        } elseif ($op == 'receive') {
            //先更改本月签到奖励领取设置
            $res = pdo_update('goouc_class_signin', array('status' => 1), array('uid' => $uid, 'month' => date('Ym01', time()), 'weid' => $_W['uniacid']));
            if ($res) {
                pdo_query("UPDATE " . tablename('goouc_class_user') . " SET card = card + " . $config['ldnum'] . " WHERE id = :id", array(':id' => $uid));
                return $this->result(0, '领取成功', array('csingn' => 0));//已领取 不能再领取了
            }
        }
    }

    public function doPageUsercrad()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        $sonid = intval($_GPC['sonid']);
        $soninfo = pdo_get('goouc_class_son', array('weid' => $_W['uniacid'], 'id' => $sonid));
        $data['uid'] = $uid;
        $data['sonid'] = $sonid;
        $data['createtime'] = time();
        $data['weid'] = $_W['uniacid'];
        $cardnum = pdo_fetch("SELECT `card` FROM " . tablename('goouc_class_user') . " WHERE id = :id AND weid = :weid", array(':id' => $uid, ':weid' => $_W['uniacid']));
        $arr['card'] = $cardnum['card'] - $soninfo['cardnum'];
        if ($arr['card'] >= 0) {
            $res = pdo_insert('goouc_class_usercard', $data);
            if ($res) {
                pdo_update('goouc_class_user', $arr, array('id' => $uid, 'weid' => $_W['uniacid']));
                return $this->result(0, '听课券已扣除', 1);
            } else {
                return $this->result(0, '听课券扣除失败', 0);
            }
        } else {
            return $this->result(0, '听课券不足', 2);
        }
    }

    public function doPageLooktime()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        $time = intval($_GPC['time']);
        $array['time'] = $time;
        $array['weid'] = $_W['uniacid'];
        $array['uid'] = $uid;
        $array['date'] = date('Ymd', strtotime("last Sunday"));
        $has = pdo_get('goouc_class_userlook', array('uid' => $uid, 'date' => $array['date']));
        if ($has) {
            $arr['time'] = $has['time'] + $time;
            pdo_update('goouc_class_userlook', $arr, array('uid' => $uid, 'date' => $array['date']));
        } else {
            pdo_insert('goouc_class_userlook', $array);
        }
        $arram['time'] = $time;
        $arram['weid'] = $_W['uniacid'];
        $arram['uid'] = $uid;
        $arram['date'] = date('Ym01', strtotime(date('Ymd')));
        $hasm = pdo_get('goouc_class_userlookm', array('uid' => $uid, 'date' => $arram['date'], 'weid' => $_W['uniacid']));
        if ($hasm) {
            $arrm['time'] = $hasm['time'] + $time;
            pdo_update('goouc_class_userlookm', $arrm, array('uid' => $uid, 'date' => $arram['date']));
        } else {
            pdo_insert('goouc_class_userlookm', $arram);
        }
    }

    public function getopenid($code)
    {
        global $_W, $_GPC;
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        function httpGet($url)
        {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
            curl_setopt($curl, CURLOPT_URL, $url);
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
        }

        $str = httpGet($api);
        return $str;
    }

    public function doPageUserpay()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $userinfo = pdo_get('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => $uid));
        $config = $this->module['config'];
        if ($config['pay_status'] == 0) {
            return $this->result(0, '暂未开启购买功能', array('error' => 0));
            exit;
        }
        if (empty($_GPC['lessonid']) && empty($_GPC['sonid'])) {
            return $this->result(0, '购买数据错误，请重新购买', array('error' => 2));
            exit;
        }
        if ($config['pay_set'] == 2 && empty($_GPC['lessonid']) && !empty($_GPC['sonid'])) {

            return $this->result(0, '当前只支持购买课程', array('error' => 3));
            exit;
        }
        if ($config['pay_set'] == 3 && !empty($_GPC['lessonid']) && empty($_GPC['sonid'])) {

            return $this->result(0, '当前只支持购买单个章节', array('error' => 4));
            exit;
        }
        $appid = $_W['account']['key'];
        $appsecret = $_W['account']['secret'];
        if ($_W['account']['level'] < 4) {
            $uniacid = $_W['oauth_account']['acid'];
            $appid = $_W['oauth_account']['key'];
            $appsecret = $_W['oauth_account']['secret'];
        }
        $payset = array('appid' => $appid, 'appsecret' => $appsecret, 'mchid' => $config['mchid'], 'shkey' => $config['pay_secret']);
        if (!empty($_GPC['lessonid'])) {

            $info = pdo_get('goouc_class_lesson', array('weid' => $_W['uniacid'], 'id' => $_GPC['lessonid']));
            $is_pay = pdo_get("goouc_os_order", array('userid' => $userinfo['id'], 'dataid' => $info['id'], 'weid' => $_W['uniacid'], 'type' => 1));
        } elseif (!empty($_GPC['sonid'])) {

            $info = pdo_get('goouc_class_son', array('weid' => $_W['uniacid'], 'id' => $_GPC['sonid']));
            $is_pay = pdo_get("goouc_os_order", array('userid' => $userinfo['id'], 'dataid' => $info['id'], 'weid' => $_W['uniacid'], 'type' => 2));
            $is_pay_lesson_son = pdo_get('goouc_os_order', array('userid' => $userinfo['id'], 'dataid' => $info['lessonid'], 'weid' => $_W['uniacid'], 'type' => 1));
            if ($is_pay['order_status'] == 1 || $is_pay_lesson_son['order_status'] == 1) {
                return $this->result(0, '你已购买过章节或文章，请勿重复购买', array('error' => 6));
            }
        }
        if (empty($info) || $info['status'] == 0) {
            return $this->result(0, '要购买的课程或章节不存在', array('error' => 5));
        }
        $order = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $uid . $info['id'];
        $money = (int)(floatval($info['pay_money']) * 100);
        $data['weid'] = $_W['uniacid'];
        if (!empty($_GPC['lessonid'])) {
            $data['dataid'] = $_GPC['lessonid'];
            $data['type'] = 1;
        } elseif (!empty($_GPC['sonid'])) {
            $data['dataid'] = $_GPC['sonid'];
            $data['type'] = 2;
        }
        $data['openid'] = $userinfo['openid'];
        $data['userid'] = $uid;
        $data['out_trade_no'] = $order;
        $data['all_money'] = $info['pay_money'];
        $data['order_status'] = 0;
        $data['createtime'] = time();
        $data['true_money'] = $info['pay_money'];
        $data['module'] = 2;
        if (!empty($is_pay)) {
            if ($is_pay['order_status'] == 0) {
                pdo_update('goouc_os_order', $data, array('id' => $is_pay['id']));
                $payment_id = $is_pay['id'];
            }
        } else {
            pdo_insert('goouc_os_order', $data);
            $payment_id = pdo_insertid();
        }
        $nonce_str = getNonceStr(32);
        $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
        $notify_url = $_W['siteroot'] . "/addons/goouc_class/wxresult.php";
        $dataurl = array(
            'appid' => $_W['account']['key'],
            'mch_id' => $config['mchid'],
            'nonce_str' => $nonce_str,
            'body' => $info['title'],
            'out_trade_no' => $order,
            'total_fee' => $money,
            'spbill_create_ip' => $spbill_create_ip,
            'notify_url' => $notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $userinfo['openid']
        );
        $sign = getSign($dataurl, $config['pay_secret']);
        $dataurl['sign'] = $sign;
        $xml = arrayToXml($dataurl);
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $res = xmlToUrl($xml, $url);
        libxml_disable_entity_loader(true);
        $xmlstr = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
        $returnarr = json_decode(json_encode($xmlstr), true);
        if ($returnarr['return_code'] == "SUCCESS" && $returnarr['result_code'] == "SUCCESS") {
            $prepay_id = $returnarr['prepay_id'];
            //$update['transaction_sn'] = $prepay_id;
            //pdo_update('goouc_os_order', $update, array('id' => $payment_id, 'weid' => $_W['uniacid']));
            $data = array(
                'appId' => $_W['account']['key'],
                'timeStamp' => '"' . time() . '"',
                'nonceStr' => $nonce_str,
                'package' => "prepay_id=" . $prepay_id,
                'signType' => 'MD5',
            );
            $paysign = getSign($data, $config['pay_secret']);
            $data['paySign'] = $paysign;
            return $this->result(0, '请求前台支付', $data);
        }
    }

    public function doPageAlreadypay()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $lessonlist = pdo_fetchall("SELECT p.lessonid,p.type,l.id,l.title,l.image FROM " . tablename('goouc_class_payment') . " p JOIN " . tablename('goouc_class_lesson') . " l ON p.lessonid = l.id  WHERE p.weid = :weid AND p.uid = :uid AND p.order_status = :order_status AND p.type = 1 ORDER BY p.compltet_time DESC", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':order_status' => 1));
        foreach ($lessonlist as $k => $v) {
            $lessonlist[$k]['son'] = pdo_fetchall("SELECT * FROM " . tablename('goouc_class_son') . " WHERE weid = :weid AND lessonid = :id", array(':weid' => $_W['uniacid'], ':id' => $v['id']));
        }
        //$slist = pdo_fetchall("SELECT sonid FROM ".tablename('goouc_class_payment')."   WHERE weid = :weid AND uid = :uid AND order_status = :order_status AND type = 2 ORDER BY compltet_time DESC",array(':weid'=>$_W['uniacid'],':uid'=>$uid,':order_status'=>1));
        $slist = pdo_fetchall("SELECT sonid FROM " . tablename('goouc_class_payment') . "   WHERE weid = :weid AND uid = :uid AND order_status = :order_status AND type = 2 ORDER BY compltet_time DESC", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':order_status' => 1));
        $array_less = array();
        foreach ($slist as $k => $v) {
            //$b = pdo_fetch("SELECT l.id as lid,l.title as ltitle,l.image as limage,s.* FROM ".tablename('goouc_class_son')." s JOIN ".tablename('goouc_class_lesson')." l ON s.lessonid = l.id WHERE s.weid = :weid AND s.id = :id",array(':weid'=>$_W['uniacid'],':id'=>$v['sonid']));
            // $a = array('id'=>$b['lid'],'title'=>$b['ltitle'],'image'=>$b['image']);
            // unset($b['lid']);
            // unset($b['ltitle']);
            // unset($b['limage']);
            // if(!array_key_exists($a['id'],$array_less)){
            //     $array_less[$a['id']] = $a;
            // }
            // $array_less[$a['id']]['son'][] = $b;
            // 加浏览量
            $a = pdo_fetch("SELECT * FROM " . tablename('goouc_class_son') . "  WHERE weid = :weid AND id = :id", array(':weid' => $_W['uniacid'], ':id' => $v['sonid']));
            $a['num'] = $a['num'] + $a['xnum'];
            if (!empty($a['image'])) {
                $a['image'] = $_W['attachurl'] . $a['image'];
            }
            $array_less[] = $a;
        }
        return $this->result(0, '用户已购买的课程与章节信息', array('lessonlist' => $lessonlist, 'sonlist' => $array_less, 'aa' => $slist));
    }

    /*我看过的章节*/
    public function doPageMystudy()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $aliyunVod = new AliyunVod($config['regionId'], $config['AccessKeyID'], $config['AccessKeySecret']);
        $uid = $_GPC['uid'];
        $slist = pdo_fetchall("SELECT sonid FROM " . tablename('goouc_class_stady') . "   WHERE weid = :weid AND uid = :uid  ORDER BY create_time DESC", array(':weid' => $_W['uniacid'], ':uid' => $uid));
        $array_less = array();
        foreach ($slist as $k => $v) {
            $a = pdo_fetch("SELECT s.id,s.title,s.num,s.xnum,s.image,`key`,sb.name as subject,l.id as lessonid FROM " . tablename('goouc_class_son') . " s JOIN " . tablename('goouc_class_lesson') . " l ON s.lessonid = l.id JOIN " . tablename('goouc_class_subject') . " sb ON l.subjectid = sb.id  WHERE s.weid = :weid AND s.id = :id", array(':weid' => $_W['uniacid'], ':id' => $v['sonid']));
            if (!empty($a)) {
                $a['num'] = $a['num'] + $a['xnum'];
                if (!empty($a['image'])) {
                    $a['image'] = $_W['attachurl'] . $a['image'];
                }
                if (!empty($a['key'])) {
                    $a['url'] = $aliyunVod->getPlayInfo($a['key']);
                } else {
                    unset($a);
                }
                $array_less[] = $a;
            }
        }
        return $this->result(0, '已经经学习过的章节', array('list' => $array_less));
    }

    /*统计用户学习过的课程*/
    public function doPageStady()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $sonid = $_GPC['sonid'];
        //是否已经记录过观看
        $has = pdo_get('goouc_class_stady', array('uid' => $uid, 'weid' => $_W['uniacid'], 'sonid' => $sonid));
        if ($has) {
            return $this->result(1, '本课程该用户已学习', 0);
        } else {
            $data = array('weid' => $_W['uniacid'], 'uid' => $uid, 'sonid' => $sonid, 'create_time' => time());
            $res = pdo_insert('goouc_class_stady', $data);
            if ($res) {
                return $this->result(0, '已记录', 1);
            } else {
                return $this->result(1, '记录失败', 0);
            }
        }
    }

    //生成海报----- 废弃了
    public function doPagePoster()
    {
        global $_W, $_GPC;
        //获取用户信息
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户ID');
        }
        $userinfo = pdo_get('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => $uid), array('headimg', 'nickname', 'qrcode', 'createtime'));
        $userinfo['nickname'] = json_decode($userinfo['nickname']);
        //用户观看时长
        $looktime = pdo_getall('goouc_class_userlookm', array('weid' => $_W['uniacid'], 'uid' => $uid), array('time'));
        $time = 0;
        foreach ($looktime as $v) {
            $time += $v['time'];
        }
        $time = ceil($time / 60);//换算成分钟
        if ($time > 100000) {
            $time = round($time / 10000, 2) . '万';
        }
        // 加入天数
        $day = ceil((time() - $userinfo['createtime']) / (24 * 60 * 60));//我已加入学习多少天
        // 获取等级设置
        $level_list = pdo_getall('goouc_class_level', array('weid' => $_W['uniacid'], 'status' => 1));
        $level_arr = array();
        foreach ($level_list as $k => $v) {
            $level_arr[$v['time']] = $v['name'];
        }
        $level_arr[$time] = '我';
        // 将数组按下表升序排序
        ksort($level_arr);
        $level = array();
        //现在数组指针在第一位
        foreach ($level_arr as $k => $v) {
            if ($k == $time) {
                break;
            }
            $level['name'] = $v;
        }
        if (empty($level['name'])) {
            $level['name'] = '学员';
            //获取签到开启的模板
            $module = pdo_getall('goouc_class_type_status', array('weid' => $_W['uniacid'], 'position' => 2, 'status' => 1));
            $poster = array();
            foreach ($module as $k => $v) {
                //获取所有的海报模板
                $poster_list = pdo_getall('goouc_class_poster', array('weid' => $_W['uniacid'], 'status' => 1, 'position' => 2), array('image', 'id', 'title', 'type'));
                foreach ($poster_list as $v) {
                    $v['image'] = $_W['attachurl'] . $v['image'];
                    $poster[] = $v;
                }
            }
            if (empty($poster)) {
                $a = array(1, 2, 3, 4, 5, 6);
                $b = $a[array_rand($a)];
                $poster_info['image'] = MODULE_URL . 'images/signin_qrcode/' . $b . '.jpg';
                $poster_info['type'] = $b;
            } else {
                $a = array_rand($poster);
                $poster_info = $poster[$a];
            }
        } else {
            $levelid = pdo_get('goouc_class_level', array('name' => $level['name'], 'weid' => $_W['uniacid']), array('id'))['id'];
            //获取所有启用的模板
            $module = pdo_getall('goouc_class_type_status', array('weid' => $_W['uniacid'], 'position' => 2, 'status' => 1), array('type'));
            foreach ($module as $k => $v) {
                //获取所有的海报模板
                $poster_list = pdo_getall('goouc_class_poster', array('weid' => $_W['uniacid'], 'status' => 1, 'position' => 2, 'type' => $v['type'], 'levelid' => $levelid), array('image', 'id', 'title', 'type'));
                foreach ($poster_list as $v) {
                    $v['image'] = $_W['attachurl'] . $v['image'];
                    $poster[] = $v;
                }
            }
            if (empty($poster)) {
                $a = array(1, 2, 3, 4, 5, 6);
                $b = $a[array_rand($a)];
                $poster_info['image'] = MODULE_URL . 'images/signin_qrcode/' . $b . '.jpg';
                $poster_info['type'] = $b;
            } else {
                $a = array_rand($poster);
                $poster_info = $poster[$a];
            }
        }
        if (empty($userinfo['qrcode'])) {
            //小程序码
            // $page = $_GPC['page'];
            $path = MODULE_ROOT . '/Qrcode/';
            if (!is_dir($path)) {
                mkdir($path);
            }
            $page = 'pages/selected/selected';//扫码直接进入首页
            $appid = $_W['account']['key'];
            $secret = $_W['account']['secret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $access_token = json_decode($this->curl_get($url), true)['access_token'];
            // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
            $data = array();
            $data['page'] = 'pages/selected/selected';//路径
            $data['scene'] = 'u=' . $uid;//场景参数
            $data = json_encode($data);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
            $da = $this->get_http_array($url, $data);
            // 生成一个图片
            $filename = 'qrcode_' . $uid . '.jpg';
            file_put_contents($path . $filename, $da);
            pdo_update('goouc_class_user', array('qrcode' => MODULE_URL . 'Qrcode/' . $filename), array('weid' => $_W['uniacid'], 'id' => $uid));
            $qrcode = MODULE_URL . 'Qrcode/' . $filename;
        } else {
            $qrcode = $userinfo['qrcode'];
        }
        $res = array('headimg' => $userinfo['headimg'], 'nickname' => $userinfo['nickname'], 'day' => $day, 'time' => $time, 'level_name' => $level['name'], 'poster' => $poster_info, 'qrcode' => $qrcode);
        return $this->result(0, '海报信息', $res);
    }

    //开启curl get请求
    public function curl_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $data;
    }

    //开启curl post请求
    public function get_http_array($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //没有这个会自动输出，不用print_r();也会在后面多个1
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        return $output;
    }

    //购买页面
    public function doPageCard()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $price = $config['cardprice'];
        $bao = pdo_getall('goouc_class_cardinfo', array('weid' => $_W['uniacid'], 'status' => 1));
        $data = array('price' => $price, 'bao' => $bao);
        return $this->result(0, '数据包', $data);
    }

    //购买听课券
    public function doPageCardpay()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $price = $config['cardprice'];
        $uid = $_GPC['uid'];
        $userinfo = pdo_get('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => $uid));
        if (empty($userinfo)) {
            return $this->result(1, '用户不存在');
        }
        $type = $_GPC['type'];//3  购买听课券包   4  购买单张
        if ($type == 3) {
            $cardid = $_GPC['cardid'];
            $cardinfo = pdo_get('goouc_class_cardinfo', array('id' => $cardid));
            if (empty($cardinfo)) {
                return $this->result(1, '你所购买的资源包不存在');
            }
            $num = $cardinfo['cardnum'];
            $money = $cardinfo['price'];
            $is_pay = pdo_get('goouc_os_order', array('weid' => $_W['uniacid'], 'userid' => $uid, 'type' => 3, 'order_status' => 0));
        } elseif ($type == 4) {
            $num = intval($_GPC['num']);
            if (empty($num)) {
                return $this->result(1, '购买数量不能小于1');
            }
            $money = $num * $price;
            $is_pay = pdo_get('goouc_os_order', array('weid' => $_W['uniacid'], 'userid' => $uid, 'type' => 4, 'order_status' => 0));
        }
        $order = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $uid . $info['id'];
        $data['weid'] = $_W['uniacid'];
        $data['type'] = $type;
        $data['dataid'] = $num;
        $data['openid'] = $userinfo['openid'];
        $data['userid'] = $uid;
        $data['out_trade_no'] = $order;
        $data['all_money'] = $money;
        $data['order_status'] = 0;
        $data['createtime'] = time();
        $data['true_money'] = $money;
        $data['module'] = 2;
        if (!empty($is_pay)) {
            if ($is_pay['order_status'] == 0) {
                pdo_update('goouc_os_order', $data, array('id' => $is_pay['id']));
                $payment_id = $is_pay['id'];
            }
        } else {
            pdo_insert('goouc_os_order', $data);
            $payment_id = pdo_insertid();
        }
        $money = (int)(floatval($money) * 100);
        $nonce_str = getNonceStr(32);
        $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
        $notify_url = $_W['siteroot'] . "/addons/goouc_class/wxresult.php";
        $dataurl = array(
            'appid' => $_W['account']['key'],
            'mch_id' => $config['mchid'],
            'nonce_str' => $nonce_str,
            'body' => '购买听课券',
            'out_trade_no' => $order,
            'total_fee' => $money,
            'spbill_create_ip' => $spbill_create_ip,
            'notify_url' => $notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $userinfo['openid']
        );
        $sign = getSign($dataurl, $config['pay_secret']);
        $dataurl['sign'] = $sign;
        $xml = arrayToXml($dataurl);
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $res = xmlToUrl($xml, $url);
        libxml_disable_entity_loader(true);
        $xmlstr = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
        $returnarr = json_decode(json_encode($xmlstr), true);
        if ($returnarr['return_code'] == "SUCCESS" && $returnarr['result_code'] == "SUCCESS") {
            $prepay_id = $returnarr['prepay_id'];
            //$update['transaction_sn'] = $prepay_id;
            //pdo_update('goouc_os_order', $update, array('id' => $payment_id, 'weid' => $_W['uniacid']));
            $data = array(
                'appId' => $_W['account']['key'],
                'timeStamp' => '"' . time() . '"',
                'nonceStr' => $nonce_str,
                'package' => "prepay_id=" . $prepay_id,
                'signType' => 'MD5',
            );
            $paysign = getSign($data, $config['pay_secret']);
            $data['paySign'] = $paysign;
            return $this->result(0, '请求前台支付', $data);
        }
    }

    // 签到页面数据
    public function doPageSignin()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '未获取到用户ID');
        }
        //查询用户当月是否签到
        $config = $this->module['config'];
        $is_signin = pdo_get('goouc_class_signin', array('weid' => $_W['uniacid'], 'uid' => $uid, 'month' => date('Ym01', time())));
        if (empty($is_signin)) {
            $data['signinstatus'] = 0;
            $data['day'] = array();
            $data['signinnum'] = 0;
        } else {
            if ($is_signin['date'] != date('Ymd', time())) {
                //当天还未签到
                $data['signinstatus'] = 0;
            } else {
                $data['signinstatus'] = 1;
            }
            //判断是否达到连续签到的需求
            $lday = $config['lday'];
            $ldnum = $config['ldnum'];
            if ($is_signin['num'] > $lday && $is_signin['status'] == 0) {
                $data['csign'] = 1;//可领取连续签到经理
            } else {
                $data['csign'] = 0;//不可领取连续签到经理
            }
            //当月签到情况
            $data['day'] = unserialize($is_signin['day']);
            $data['month'] = date('Y-m', time());
            $data['signinnum'] = $is_signin['num'];
        }
        $data['lnum'] = $config['lnum'];//每天签到获得奖励数
        $data['lday'] = $config['lday'];
        $data['ldnum'] = $config['ldnum'];
        // 返回精品推荐课程
        $data['lesson'] = pdo_fetchall("SELECT `id`,`image` FROM " . tablename('goouc_class_lesson') . " WHERE weid=:weid AND status=1 AND recommend=1 ORDER BY `order` DESC LIMIT 0,3", array(':weid' => $_W['uniacid']));
        foreach ($data['lesson'] as $k => $v) {
            $data['lesson'][$k]['image'] = $_W['attachurl'] . $v['image'];
            $num = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('goouc_class_son') . " where weid=:weid AND lessonid=:lessonid", array(':weid' => $_W['uniacid'], ':lessonid' => $v['id']));
            if ($num <= 0) {
                unset($data['lesson'][$k]);
            }
        }
        return $this->result(0, '签到页面数据', $data);
    }

    //课程分享海报
    public function doPageLessonposter()
    {
        global $_W, $_GPC;
        $lessonid = $_GPC['lessonid'];
        $uid = $_GPC['uid'];
        $userinfo = pdo_get('goouc_class_user', array('id' => $uid, 'weid' => $_W['uniacid']));
        if (empty($userinfo)) {
            return $this->result(1, '用户不存在');
        }
        $lessoninfo = pdo_get('goouc_class_lesson', array('weid' => $_W['uniacid'], 'id' => $lessonid));
        $subject = pdo_get('goouc_class_subject', array('weid' => $_W['uniacid'], 'id' => $lessoninfo['subjectid']), array('name'));
        $teacher = pdo_get('goouc_class_teacher', array('weid' => $_W['uniacid'], 'id' => $lessoninfo['teacherid']), array('name'));
        if (empty($lessoninfo)) {
            return $this->result(1, '分享的课程不存在');
        }
        $sonnum = pdo_getall('goouc_class_son', array('lessonid' => $lessonid, 'weid' => $_W['uniacid'], 'status' => 1));
        $sonnum = count($sonnum);
        // $sonnum = pdo_fetchcolumn("SELECT COUNT(*) FROM ".tablename('goouc_class_son').' where weid=:weid AND status=1 AND lessonid=:lessonid',array(':weid'=>$_W['uniacid'],':lessonid'=>$lessonid));
        $res['sonnum'] = $sonnum;
        // 先获取已开启的模板
        $module = pdo_getall('goouc_class_type_status', array('weid' => $_W['uniacid'], 'position' => 1, 'status' => 1), array('type'));
        //获取开启末班下的所有图片
        $poster = array();
        foreach ($module as $k => $v) {
            $poster_list = pdo_getall('goouc_class_poster', array('weid' => $_W['uniacid'], 'status' => 1, 'type' => $v['type'], 'position' => 1), array('image', 'id', 'title', 'type'));
            foreach ($poster_list as $v) {
                $v['image'] = $_W['attachurl'] . $v['image'];
                $poster[] = $v;
            }
        }
        $res['poster'] = $poster;
        $res['headimg'] = $userinfo['headimg'];
        $res['nickname'] = json_decode($userinfo['nickname']);
        $res['lessontitle'] = $lessoninfo['title'];
        $res['lessondesc'] = $lessoninfo['desc'];
        $res['lessonimage'] = $_W['attachurl'] . $lessoninfo['share_image'];
        $configweb = $this->module['config'];
        $res['desc'] = '邀请你来' . $configweb['webname'] . '学习更多的知识';
        $res['sonnum'] = $sonnum;
        $res['subject_name'] = $subject['name'];
        $res['teacher_name'] = $teacher['name'];
        // $page = $_GPC['page'];
        $path = MODULE_ROOT . '/Qrcode/';
        if (!is_dir($path)) {
            mkdir($path);
        }
        $filename = 'qrcode' . $uid . '_' . $lessonid . '.jpg';
        if (!file_exists($path . $filename)) {
            $sonid = $_GPC['sonid'];
            // $page = $_GPC['page'];//扫码直接进入首页
            $appid = $_W['account']['key'];
            $secret = $_W['account']['secret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $access_token = json_decode($this->curl_get($url), true)['access_token'];
            // header('content-type:image/jpg');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
            $data = array();
            $data['page'] = 'pages/selected/selected';//路径
            // $data['path'] = '';//路径
            // $data['scene'] = 'uid='.$uid.'&lid='.$lessonid.'&page=SD';//场景参数
            $data['scene'] = 'u=' . $uid . '&l=' . $lessonid . '&p=SD&s=' . $sonid;
            $data = json_encode($data);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
            $da = $this->get_http_array($url, $data);
            // 生成一个图片
            file_put_contents($path . $filename, $da);
        }
        $res['qrcode'] = MODULE_URL . 'Qrcode/' . $filename;
        return $this->result(0, '分享海报信息', $res);
    }

    /*补救没有头像的用户信息*/
    public function doPageUpdateimg()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $data['nickname'] = json_encode(trim($_GPC['nickname']));
        $data['headimg'] = trim($_GPC['avatar']);
        //获取用户信息
        $info = pdo_get('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => $uid));
        // 修补被分享者没有头像 昵称的问题
        if (!empty($info['phone']) && !empty('name') && $info['new_status'] == 1 && (empty($info['nickname']) || empty($info['headimg']))) {
            $data['new_status'] = 0;
            $res = pdo_update('goouc_class_user', $data, array('id' => $uid, 'weid' => $_W['uniacid']));
        }
        return $this->result(0, '数据', $res);
    }

    // 用户每次筛选记录上次筛选的classid
    public function doPageChangeclass()
    {
        global $_W, $_GPC;
        $uid = intval($_GPC['uid']);
        $classid = intval($_GPC['classid']);
        if (empty($uid)) {
            return $this->result(1, '用户ID不存在');
        }
        if (!empty($classid)) {
            $data['classid'] = $classid;
            $res = pdo_update('goouc_class_user', $data, array('weid' => $_W['uniacid'], 'id' => $uid));
        }
        if ($res) {
            return $this->result(0, '已记录', $res);
        } else {
            return $this->result(1, '记录失败');
        }
    }

    public function doPageIndex1()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $aliyunVod = new AliyunVod($config['regionId'], $config['AccessKeyID'], $config['AccessKeySecret']);
        $contion = "weid = :weid AND status = 1";
        $params[':weid'] = $_W['uniacid'];
        $op = empty($_GPC['op']) ? 'city' : $_GPC['op'];
        if ($op == 'city') {
            $city = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_city') . " WHERE " . $contion, $params);
            if (empty($city)) {
                $city = pdo_getall('goouc_class_city', array('weid' => $_W['uniacid']));
            }
            if (count($city) == 1) {
                $citystatus = 1;
                $city = $city;
            } elseif (count($city) > 1) {
                $city = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_city') . " WHERE " . $contion, $params);
                $citystatus = 2;
            }
            return $this->result(0, '城市信息', array('city' => $city, 'status' => $citystatus));
        } elseif ($op == 'class') {
            $class = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_class') . " WHERE " . $contion, $params);
            return $this->result(0, '年级列表', array('class' => $class, $contion, $params));
        } elseif ($op == 'subject') {
            $classid = $_GPC['classid'];
            if (!empty($classid)) {
                $contion .= " AND id = :id";
                $params[':id'] = $classid;
                $classlist = pdo_fetch("SELECT `id`,`name`,`subjectid` FROM " . tablename('goouc_class_class') . " WHERE " . $contion, $params);
                $arr_subject = unserialize($classlist['subjectid']);
                foreach ($arr_subject as $su => $us) {
                    $subject[] = pdo_fetch("SELECT `id`,`name` FROM " . tablename("goouc_class_subject") . " WHERE id = :id", array(':id' => $us));
                }
            } else {
                $subject = pdo_getall('goouc_class_subject', array('weid' => $_W['uniacid'], 'status' => 1));
            }
            return $this->result(0, '学科列表', array('subject' => $subject, $contion, $params));
        } elseif ($op == 'teacher') {
            $cityid = $_GPC['cityid'];
            $subjectid = $_GPC['subjectid'];
            if (!empty($cityid)) {
                $contion .= " AND cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($subjectid)) {
                $contion .= " AND subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            $teacher = pdo_fetchall("SELECT `id`,`name` FROM " . tablename('goouc_class_teacher') . " WHERE " . $contion, $params);
            return $this->result(0, '老师信息', array('teacher' => $teacher, $contion, $params));
        } elseif ($op == 'semester') {
            $semester = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_semester') . " WHERE " . $contion, $params);
            return $this->result(0, '班期列表', array('semester' => $semester, $contion, $params));
        } elseif ($op == 'voidtype') {
            $voidtype = pdo_fetchall('SELECT `id`,`name` FROM ' . tablename('goouc_class_voidtype') . " WHERE " . $contion, $params);
            return $this->result(0, '模式列表', array('voidtype' => $voidtype, $contion, $params));
        } elseif ($op == 'year') {
            $cityid = $_GPC['cityid'];
            $classid = $_GPC['classid'];
            $subjectid = $_GPC['subjectid'];
            $teacherid = $_GPC['teacherid'];
            $semesterid = $_GPC['semesterid'];
            $voidtypeid = $_GPC['voidtypeid'];
            if (!empty($cityid)) {
                $contion .= " AND cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($classid)) {
                $contion .= " AND classid LIKE '%\"" . $classid . "\"%'";
            }
            if (!empty($subjectid)) {
                $contion .= " AND subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            if (!empty($teacherid)) {
                $contion .= " AND teacherid = :teacherid";
                $params[':teacherid'] = $teacherid;
            }
            if (!empty($semesterid)) {
                $contion .= " AND semesterid = :semesterid";
                $params[':semesterid'] = $semesterid;
            }
            if (!empty($voidtypeid)) {
                $contion .= " AND voidtypeid = :voidtypeid";
                $params[':voidtypeid'] = $voidtypeid;
            }
            $year_arr = pdo_fetchall("SELECT `yearid` FROM " . tablename('goouc_class_lesson') . " WHERE " . $contion . " GROUP BY `yearid`", $params);
            $year = array();
            foreach ($year_arr as $k => $v) {
                $year[$k]['name'] = $v['yearid'];
                $year[$k]['id'] = $v['yearid'];
            }
            return $this->result(0, '年份列表', array('year' => $year, $contion, $params));
        } elseif ($op == 'lesson') {
            $cityid = $_GPC['cityid'];
            $classid = $_GPC['classid'];
            $subjectid = $_GPC['subjectid'];
            $teacherid = $_GPC['teacherid'];
            $semesterid = $_GPC['semesterid'];
            $voidtypeid = $_GPC['voidtypeid'];
            $yearid = $_GPC['yearid'];
            if (!empty($cityid)) {
                $contion .= " AND cityid = :cityid";
                $params[':cityid'] = $cityid;
            }
            if (!empty($classid)) {
                $contion .= " AND classid LIKE '%\"" . $classid . "\"%'";
            }
            if (!empty($subjectid)) {
                $contion .= " AND subjectid = :subjectid";
                $params[':subjectid'] = $subjectid;
            }
            if (!empty($teacherid)) {
                $contion .= " AND teacherid = :teacherid";
                $params[':teacherid'] = $teacherid;
            }
            if (!empty($semesterid)) {
                $contion .= " AND semesterid = :semesterid";
                $params[':semesterid'] = $semesterid;
            }
            if (!empty($voidtypeid)) {
                $contion .= " AND voidtypeid = :voidtypeid";
                $params[':voidtypeid'] = $voidtypeid;
            }
            if (!empty($yearid)) {
                $contion .= " AND yearid = :yearid";
                $params[':yearid'] = $yearid;
            }
            $pageindex = max(1, intval($_GPC['page']));
            $psize = 4;
            $contion .= ' AND semesterid != 0 AND  voidtypeid != 0 AND teacherid != 0 AND subjectid != 0 AND cityid != 0';
            $lesson = pdo_fetchall("SELECT `id`,`title`,`status` FROM " . tablename('goouc_class_lesson') . " WHERE " . $contion . " ORDER BY `order` DESC LIMIT " . ($pageindex - 1) * $psize . ',' . $psize, $params);
            foreach ($lesson as $k => $v) {
                $lesson[$k]['image'] = $_W['attachurl'] . $v['image'];
                $lesson[$k]['son'] = pdo_fetchall("SELECT `id`,`title`,`image`,`key`,`num`,`xnum`,`vediotime` FROM " . tablename("goouc_class_son") . " WHERE lessonid = :lessonid AND weid = :weid AND status = 1 ORDER BY `orders` DESC", array(':lessonid' => $v['id'], ':weid' => $_W['uniacid']));
                $lesson[$k]['sonnum'] = count($lesson[$k]['son']);
                foreach ($lesson[$k]['son'] as $kk => $vv) {
                    $lesson[$k]['son'][$kk]['num'] = $vv['num'] + $vv['xnum'];
                    if (!empty($lesson[$k]['son'][$kk]['image'])) {
                        $lesson[$k]['son'][$kk]['image'] = $_W['attachurl'] . $vv['image'];
                    } elseif (empty($lesson[$k]['son'][$kk]['coverurl'])) {
                        try {
                            $video = $aliyunVod->getPlayInfo($vv['key']);
                            $lesson[$k]['son'][$kk]['coverurl'] = $video->VideoBase->CoverURL;
                            pdo_update('goouc_class_son', array('coverurl' => $video->VideoBase->CoverURL), array('weid' => $_W['uniacid'], 'id' => $vv['id']));
                        } catch (Exception $e) {
                            unset($lesson[$k]['son'][$kk]);
                            continue;
                        }
                    }
                    //判断表中有没有视频时长 封面图片的信息
                    if ($vv['vediotime'] == '0.00') {
                        try {
                            $video = $aliyunVod->getPlayInfo($vv['key']);
                            $data['vediotime'] = $video->PlayInfoList->PlayInfo[0]->Duration;
                            $lesson[$k]['son'][$kk]['vediotime'] = $data['vediotime'];
                            //更新数据表
                            pdo_update('goouc_class_son', $data, array('weid' => $_W['uniacid'], 'id' => $vv['id']));
                        } catch (Exception $e) {
                            unset($lesson[$k]['son'][$kk]);
                            continue;
                        }
                    }
                }
            }
            $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename("goouc_class_lesson") . " WHERE " . $contion, $params);
            $page = ceil($total / $psize);
            return $this->result(0, '数据列表', array('lesson' => $lesson, 'page' => $page, $contion, $params));
        }
    }

    //退款方法
    public function refund($uid, $id)
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $info = pdo_fetch("select ugi.out_trade_no,o.order_status,o.all_money,o.true_money,o.id,o.transaction_sn,ugi.groupid from " . tablename($this->t_user_group_info) . " ugi JOIN " . tablename($this->t_order) . " o ON ugi.out_trade_no = o.out_trade_no where ugi.id = :id AND ugi.uid = :uid AND ugi.refund_status = :status", [':id' => $id, ':uid' => $uid, ':status' => 2]);
        if (!empty($info)) {
            $out_trade_no = $info['out_trade_no'];
            $total_fee = intval($info['true_money'] * 100);
            $refund_fee = intval($info['true_money'] * 100);
            $WxPayConfig = new \WxPayConfig();
            $WxPayConfig->AppId = $appid;
            $WxPayConfig->AppSecret = $secret;
            $WxPayConfig->Mchid = $config['mchid'];
            $WxPayConfig->PaySecret = $config['pay_secret'];
            $WxPayConfig->sslCertPath = IA_ROOT . '/' . $config['wxcert'];
            $WxPayConfig->sslKeyPath = IA_ROOT . '/' . $config['wxkey'];
            $input = new \WxPayRefund();
            $input->SetTransaction_id($info['transaction_sn']);
            $input->SetOut_refund_no("refund" . date("YmdHis"));
            $input->SetOut_trade_no($out_trade_no);
            $input->SetOp_user_id($WxPayConfig->GetMerchantId());
            $input->SetTotal_fee($total_fee);
            $input->SetRefund_fee($refund_fee);
            $result = WxPayApi::refund($WxPayConfig, $input);
            file_put_contents(IA_ROOT . '/addons/goouc_class/tuikuan.txt', json_encode($result));
            if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                pdo_update($this->t_order, array('order_status' => 2, 'refundtime' => time()), array('id' => $info['id']));
                pdo_update($this->t_user_group_info, array('refund_status' => 1, 'refund_time' => time()), ['id' => $id]);
                //标记拼团表，是否执行过退款
                pdo_update($this->t_user_group, array('refund_status' => 1), ['id' => $info['groupid']]);
            }
        }
    }

    public function doPageUserUnderline()
    {
        global $_W, $_GPC;
        $op = empty($_GPC['op']) ? 'list' : $_GPC['op'];
        $uid = intval($_GPC['uid']);
        if ($op == 'list') {
            $phone = pdo_getcolumn('goouc_class_user', array('weid' => $_W['uniacid'], 'id' => intval($uid)), 'phone');
            if (empty($phone)) {
                return $this->result(1, '请先绑定手机号');
            }
            $lessonlist = pdo_fetchall("select l.id,l.title,l.image from " . tablename('goouc_class_lesson_underline_student') . " s LEFT JOIN " . tablename($this->t_lesson) . " l ON s.lesson_id = l.id where s.weid = :weid and s.phone = :phone AND l.id is NOT NULL ", array(':weid' => $_W['uniacid'], ':phone' => $phone));
            if (!empty($lessonlist)) {
                foreach ($lessonlist as $k => $v) {
                    if ($_W['uniacid'] == 20) {
                        $lessonlist[$k]['image'] = $this->qiniu_url . $v['image'];
                    } else {
                        $lessonlist[$k]['image'] = $_W['attachurl'] . $v['image'];
                    }
                    $lessonlist[$k]['studynum'] = pdo_getcolumn('goouc_class_lesson_underline_student', array('weid' => $_W['uniacid'], 'lesson_id' => $v['id']), 'COUNT(id)');
                    $time = pdo_fetchcolumn("select study_time from " . tablename($this->t_user_study_speed) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid order by study_time DESC ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $v['id']));
                    if (!empty($time)) {
                        $lessonlist[$k]['studytime'] = date('Y年m月d日 H:i:s', $time);
                    } else {
                        $lessonlist[$k]['studytime'] = 0;
                    }
                    if ($v['is_only'] == 1) {
                        $son_vediotime = pdo_fetchcolumn("select vediotime from " . tablename($this->t_son) . " where lessonid = :lessonid ", array(':lessonid' => $v['id']));
                        $lessonlist[$k]['speed'] = $lessonlist[$k]['speed'] / $son_vediotime;
                    } else {
                        $study_total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_user_study_speed) . " where weid = :weid AND uid = :uid AND lessonid = :lessonid ", array(':weid' => $_W['uniacid'], ':uid' => $uid, ':lessonid' => $v['id']));
                        $total = pdo_fetchcolumn("select COUNT(*) from " . tablename($this->t_son) . " where  lessonid = :lessonid ", array(':lessonid' => $v['id']));
                        if (empty($study_total) || empty($total)) {
                            $lessonlist[$k]['speed'] = 0;
                        } else {
                            $lessonlist[$k]['speed'] = $study_total / $total;
                        }
                    }
                }
            }
            return $this->result(0, '获取数据', $lessonlist);
        }
    }

    /*
     * 习题版新我的课程页面
     * */
    public function doPagePracticeMyLesson()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        //获取已报名的课程
        $contion = 's.weid = :weid AND s.uid = :uid';
        $params = [':weid' => $weid, ':uid' => $uid];
        $lessonList = pdo_fetchall("select s.id,s.uid,sj.name as subjectname,l.title as ltitle,l.id as lid from " . tablename($this->t_signup) . " s LEFT JOIN " . tablename($this->t_lesson) . " l ON s.lessonid = l.id LEFT JOIN " . tablename($this->t_subject) . " sj ON l.subjectid = sj.id where " . $contion, $params);
        //$lessonList = pdo_fetchall("select count(p.id) as pnum, s.id,s.uid,sj.name as subjectname,l.title as ltitle,l.id as lid from " . tablename($this->t_signup) . " s LEFT JOIN " . tablename($this->t_lesson) . " l ON s.lessonid = l.id LEFT JOIN " . tablename('goouc_class_practice') . "p ON p.lessonid = l.id LEFT JOIN  ". tablename($this->t_subject) . " sj ON l.subjectid = sj.id LEFT JOIN".tablename($this->t_son)." so ON so.lessonid = l.id where " . $contion. " group by l.id", $params);
        //线下课
        $phone = pdo_fetchcolumn("select phone from " . tablename('goouc_class_user') . "  where id = :uid", array(':uid' => $uid));
        $lparams = [':weid' => $weid, ':phone' => $phone, ':is_underline' => 1];
        $underlineList = pdo_fetchall("select sj.name as subjectname,l.title as ltitle,l.id as lid from " . tablename('goouc_class_lesson_underline_student') . " us LEFT JOIN " . tablename('goouc_class_lesson') . " l ON us.lesson_id = l.id LEFT JOIN " . tablename('goouc_class_subject') . " sj ON l.subjectid = sj.id where us.weid = :weid AND us.phone = :phone AND l.is_underline = :is_underline", $lparams);
        //$underlineList = pdo_fetchall("select count(p.id) as pnum, sj.name as subjectname,l.title as ltitle,l.id as lid from " . tablename('goouc_class_lesson_underline_student') . " us LEFT JOIN " . tablename('goouc_class_lesson') . " l ON us.lesson_id = l.id LEFT JOIN " . tablename('goouc_class_practice'). "p ON p.lessonid = l.id LEFT JOIN  " . tablename('goouc_class_subject') . " sj ON l.subjectid = sj.id where us.weid = :weid AND us.phone = :phone AND l.is_underline = :is_underline". " group by l.id", $lparams);
        $lessonList = array_merge($lessonList, $underlineList);
        //把存在习题的课程放在一个数组里
        $practiceLesson = [];
        foreach ($lessonList as $ks => $vs) {
            $pnum = pdo_fetchall("select p.id from " . tablename('goouc_class_practice') . " p LEFT JOIN " . tablename('goouc_class_son') . " s ON p.sonid = s.id WHERE s.weid = :weid AND s.status = :status AND s.lessonid = :lid ", array(':weid' => $weid, ':status' => 1, ':lid' => $vs['lid']));
            if (count($pnum) > 0) {
                $practiceLesson[] = $vs;
            }
        }
        // var_dump($practiceLesson);die;
        //把存在习题的课程放在一个数组里
//        $practiceLesson = [];
//        foreach ($totalList as $kv => $vv) {
//            if ($vv['pnum'] > 0) {
//                $practiceLesson[] = $vv;
//            }
//        }
        foreach ($practiceLesson as &$v) {
            //章节总数量
            $tsql = "SELECT COUNT(*) FROM " . tablename('goouc_class_son') . " WHERE weid = :weid AND lessonid = :lessonid AND status = :status";
            $chaptertotal = pdo_fetchcolumn($tsql, array(':weid' => $weid, ':lessonid' => $v['lid'], ':status' => 1));
            //课程总星星数量
            $v['totalStar'] = 3 * $chaptertotal;
            //会员该课程获取到的星星数量
            $userstar = pdo_fetch("select sum(num) as totalnum from " . tablename('goouc_class_user_star') . " WHERE weid = :weid AND lessonid = :lessonid AND uid = :uid AND status = :status", array(':weid' => $weid, ':uid' => $uid, ':lessonid' => $v['lid'], ':status' => 1));
            $v['user_star'] = empty($userstar['totalnum']) ? 0 : $userstar['totalnum'];
            //学习进度条
            $studySon = pdo_fetchcolumn("select COUNT(*) as studySon FROM " . tablename('goouc_class_stady') . " cs LEFT JOIN " . tablename('goouc_class_son') . " s ON cs.sonid = s.id LEFT JOIN " . tablename('goouc_class_lesson') . " l ON s.lessonid = l.id where cs.weid = :weid AND cs.uid = :uid AND l.id = :lid AND s.status = :status", array(':weid' => $weid, ':uid' => $uid, ':lid' => $v['lid'], ':status' => 1));
            if ($chaptertotal) {
                $jindu = empty($chaptertotal) ? 0 : ($studySon / $chaptertotal);
                $v['jindu'] = floor($jindu * 100) / 100;
            } else {
                $v['jindu'] = 0;
            }
            //最近一场直播时间
            //$nearvideo = pdo_fetch("select starttime from " . tablename('goouc_class_son') . " WHERE weid = :weid AND lessonid = :lessonid AND status = :status AND sontype <> :sontype AND starttime > :starttime AND starttime <= :endtime ORDER BY starttime asc limit 1", array(':weid' => $weid, ':lessonid' => $v['lid'], ':sontype' => 2, ':status' => 1, ':starttime' => strtotime(date('Y-m-d 00:00:00', time())), ':endtime' => strtotime(date('Y-m-d 23:59:59', time()))));
            //$v['video'] = empty($nearvideo['starttime']) ? 0 : date('H:s', $nearvideo['starttime']);//当天的直播章节时间
            //该课程学习状态
            $studyStatus = pdo_fetch("select id FROM " . tablename('goouc_class_user_study_speed') . " WHERE weid = :weid AND lessonid = :lessonid AND uid = :uid limit 1", array(':weid' => $weid, ':lessonid' => $v['lid'], ':uid' => $uid));
            $v['studyStatus'] = empty($studyStatus['id']) ? 2 : 1;//1:已学习 2:未学习
        }
        return $this->result(0, '习题课程数据', $practiceLesson);
    }

    /*
     * 课程详情页接口
     * 参数：lessonid,status,weid,orders
     * 1.该课程总共学习多长时间，总共有多少章节，学习了多少章节，算出百分比
     * 2.该课程总共获得的星星数量，总星星数量
     * 3.若是直播课程：直播等待，直播进行中（直播没开始的习题按钮不能点）
     * 4.录播课程
     * 4.习题是否做过状态，做过的话获取获得星星的数量
     * */
    public function doPagePracticeLessonInfo()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $lessonid = $_GPC['lid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        if (empty($lessonid)) {
            return $this->result(1, '课程id未获取到', array('code' => 3001, 'msg' => '课程id未获取到'));
        }
        $weid = $_W['uniacid'];
        //章节列表
        $contion = " weid = :weid AND lessonid = :lessonid AND status = :status ";
        $params = [':weid' => $weid, ':lessonid' => $lessonid, ':status' => 1];
        $sonList = pdo_fetchall("select * from " . tablename('goouc_class_son') . "  where weid = :weid AND lessonid = :lessonid AND status = :status  order by orders desc", $params);
        //课程总章节数
        $totalSon = pdo_fetchcolumn("select count(*) as totalSon  from " . tablename('goouc_class_son') . "  where " . $contion, $params);
        //会员学习总时长（只统计观看完的）统计百分比
        $paramsStady = [':weid' => $weid, ':lid' => $lessonid, ':uid' => $uid];
        $studytime = pdo_fetchcolumn("select sum(s.vediotime) as studyTime  from " . tablename('goouc_class_stady') . " cs LEFT JOIN " . tablename('goouc_class_son') . " s ON cs.sonid = s.id LEFT JOIN " . tablename('goouc_class_lesson') . " l ON s.lessonid = l.id where cs.weid = :weid AND cs.uid = :uid AND l.id = :lid", $paramsStady);
        //进度条
        $studySon = pdo_fetchcolumn("select COUNT(*) as studySon FROM " . tablename('goouc_class_stady') . " cs LEFT JOIN " . tablename('goouc_class_son') . " s ON cs.sonid = s.id LEFT JOIN " . tablename('goouc_class_lesson') . " l ON s.lessonid = l.id where cs.weid = :weid AND cs.uid = :uid AND l.id = :lid AND s.status = :status", array(':weid' => $weid, ':uid' => $uid, ':lid' => $lessonid, ':status' => 1));
        if ($totalSon) {
            $jindu = floor(($studySon / $totalSon) * 100) / 100;
        } else {
            $jindu = 0;
        }
        //星星总数
        $totalstar = 3 * $totalSon;
        //做题获得星星总数
        $userstar = pdo_fetchcolumn("select sum(num) as userstar from " . tablename('goouc_class_user_star') . " WHERE weid = :weid AND lessonid = :lessonid AND uid = :uid AND status = :status", array(':weid' => $weid, ':uid' => $uid, ':lessonid' => $lessonid, ':status' => 1));
        foreach ($sonList as $k => &$v) {
            //判断有没有习题
            $havepractice = pdo_get('goouc_class_practice', array('weid' => $weid, 'sonid' => $v['id'], 'status' => 1, 'is_delete' => 1), array('id'));
            $v['havepractice'] = $havepractice['id'];
            if (empty($havepractice)) {
                unset($sonList[$k]);
            }
            if ($v['sontype'] == 1) {
                $v['livetype'] = 1;//直播课程
                if ($v['starttime'] > time()) {
                    $v['livestatus'] = 2;//直播未开始
                } elseif (($v['starttime'] + 20 * 60) < time()) {
                    //把章节下架（直播开始时间超了20分钟还未开始）
                    pdo_update('goouc_class_son', array('status' => 2), array('id' => $v['id']));
                } else {
                    $v['livestatus'] = 1;//直播开始
                }
                //$v['starttime'] = date('Y-m-d H:i', $v['starttime']);
            } else {
                $v['livetype'] = 0;//录播
                //$v['livestatus'] = 0;//这个值需要吗
            }
            //判断习题是否做过
            $checkPractice = pdo_fetchcolumn("select id from " . tablename('goouc_class_practice_record') . " WHERE weid = :weid AND sonid = :sonid AND uid = :uid AND status = :status limit 1", array(':weid' => $weid, ':uid' => $uid, ':sonid' => $v['id'], ':status' => 1));
            if ($checkPractice) {
                $v['practicestatus'] = 1;//习题已经做过
            } else {
                $v['practicestatus'] = 2;//习题没做过
            }
            //该章节星星数量
            $getstar = pdo_fetchcolumn("select num from " . tablename('goouc_class_user_star') . " WHERE weid = :weid AND sonid = :sonid AND uid = :uid AND status = :status ", array(':weid' => $weid, ':uid' => $uid, ':sonid' => $v['id'], ':status' => 1));
            $v['getstar'] = empty($getstar) ? 0 : $getstar;
            //判断是不是可以做习题
//            $checkstudy = pdo_fetchcolumn("select id FROM " . tablename('goouc_class_stady') . " where weid = :weid AND uid = :uid AND sonid = :sonid", array(':weid' => $weid, ':uid' => $uid, ':sonid' => $v['id']));
//            $v['dostatus'] = empty($checkstudy) ? 2 : 1;//1可以做 2不可以做
            //暂时先把做题打开
            $v['dostatus'] = 1;
        }
        $sonListNew = [];
        foreach ($sonList as $v) {
            $sonListNew[] = $v;
        }
        $lesson = pdo_get('goouc_class_lesson', array('weid' => $weid, 'id' => $lessonid), array('is_only', 'fic_study_num', 'study_num', 'pay_num'));
        $signupnum = pdo_fetchcolumn("select count(*) from " . tablename($this->t_signup) . " where lessonid = :lessonid ", array(':lessonid' => $lessonid));
        $data = [
            'sonlist' => $sonListNew,
            'studytime' => $studytime,//会员学习总时长
            'jindu' => $jindu,
            'is_only' => $lesson['is_only'],//1为单节课  2为系列课
            'studynum' => $lesson['fic_study_num'] + $signupnum,
            'totalstar' => $totalstar,
            'userstar' => empty($userstar) ? 0 : $userstar
        ];
        return $this->result(0, '课程章节数据', $data);
    }

    /*
     * 章节习题接口
     *
     * 参数：lessonid,sonid,weid,status=1
     * 填空【】
     * 选项格式
     *
     */
    public function doPagePracticeList()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $sonid = $_GPC['sonid'];
        $lessonid = $_GPC['lid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        if (empty($lessonid)) {
            return $this->result(1, '课程id未获取到', array('code' => 3001, 'msg' => '课程id未获取到'));
        }
        if (empty($sonid)) {
            return $this->result(1, '章节id未获取到', array('code' => 3001, 'msg' => '章节id未获取到'));
        }
        $types_config = array('1' => '判断题', '2' => '单选题', '3' => '多选题', '4' => '填空题');
        $weid = $_W['uniacid'];
        $params = [':weid' => $weid, ':sonid' => $sonid, ':lessonid' => $lessonid, ':status' => 1];
        $practiceList = pdo_fetchall("select * from " . tablename('goouc_class_practice') . "  where weid = :weid AND sonid = :sonid AND status = :status AND lessonid = :lessonid", $params);
        foreach ($practiceList as $k => &$v) {
            if ($v['thumb']) {
                $v['thumb'] = $this->getImgUrl($v['thumb']);
            }
            if ($v['type'] == 2 || $v['type'] == 3) {
                $v['items'] = unserialize($v['items']);
                if ($v['isimg'] == 1) {
                    $img_items = unserialize($v['img_items']);
                    foreach ($img_items as &$vi) {
                        $vi['p'] = $this->getImgUrl($vi['p']);
                    }
                    $v['img_items'] = $img_items;
                }
            } elseif ($v['type'] == 4) {
                //计算填空数
                $v['answersNum'] = explode("、", $v['answer']);
            }
            $v['practiceType'] = $types_config[$v['type']];
        }
        return $this->result(0, '章节习题列表', $practiceList);
    }

    /*
     * 交卷接口
     *
     * 获取到的数组便利对比数据库的答案
     * 1.把答题情况记录到答疑记录表里
     * 2.记录每个习题答对多少人，总共答题人数
     * 3.把错题单独记录到做题表里（记录lid,sonid,uid,ctime）//每次做题都把错题记录下来
     * 4.若是表里已经有该会员该章节的星星数据，则不再存储
     * 5.计算应该获取星星数量：全对三颗星，一半以下一颗星，一半以上小于100%两颗星，全错0星
     * 6.统计好后把答题记录最新数据返给前台
     * */
    public function doPagePracticeHandIn()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $sonid = $_GPC['sonid'];
        $lessonid = $_GPC['lid'];
        $answer = json_decode(htmlspecialchars_decode($_GPC['allAnswer']), true);
        $allAnswer = [];
        foreach ($answer as $key => &$val) {
            $allAnswer[$val['id']] = $val;
        }
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        if (empty($lessonid)) {
            return $this->result(1, '课程id未获取到', array('code' => 3001, 'msg' => '课程id未获取到'));
        }
        $types_config = array('1' => '判断题', '2' => '单选题', '3' => '多选题', '4' => '填空题');
        $weid = $_W['uniacid'];
        if (empty($sonid)) {
            return $this->result(1, '章节id未获取到', array('code' => 3001, 'msg' => '章节id未获取到'));
        }
        $params = [':weid' => $weid, ':sonid' => $sonid, ':lessonid' => $lessonid, ':status' => 1];
        $practiceList = pdo_fetchall("select * from " . tablename('goouc_class_practice') . "  where weid = :weid AND sonid = :sonid AND status = :status AND lessonid = :lessonid", $params);
        $num = 0;//答对的提数
        foreach ($practiceList as &$v) {
            if ($v['answer'] == $allAnswer[$v['id']]['answer']) {
                $data['data'][] = ['status' => 1];
                $rdata[$v['id']] = ['id' => $v['id'], 'status' => 1, 'uanswer' => $allAnswer[$v['id']]['answer']];
                $num++;
            } else {
                $data['data'][] = ['status' => 0];
                $rdata[$v['id']] = ['id' => $v['id'], 'status' => 0, 'uanswer' => $allAnswer[$v['id']]['answer']];
                //先判断是不是存在
                $paramsfalse = array('weid' => $weid, 'uid' => $uid, 'sonid' => $sonid, 'lessonid' => $lessonid, 'practiceid' => $v['id']);
                $checkfalse = pdo_get('goouc_class_practice_false_record', $paramsfalse, array('id', 'is_delete'));
                //保存错题记录
                $falseInsert = [
                    'weid' => $weid,
                    'uid' => $uid,
                    'lessonid' => $lessonid,
                    'sonid' => $sonid,
                    'practiceid' => $v['id'],
                    'answer' => $v['answer'],
                    'useranswer' => $allAnswer[$v['id']]['answer'],
                    'createtime' => time()
                ];
                if (!$checkfalse) {
                    pdo_insert('goouc_class_practice_false_record', $falseInsert);
                } else {
                    if ($checkfalse['is_delete'] == 2) {
                        $falseInsert['is_delete'] = 1;
                    }
                    pdo_update('goouc_class_practice_false_record', $falseInsert, array('id' => $checkfalse['id']));
                }
            }
        }
        //判断这个学生有没做过这个章节的习题
        $checkR = pdo_get('goouc_class_practice_record', array('weid' => $weid, 'uid' => $uid, 'lessonid' => $lessonid, 'sonid' => $sonid, 'status' => 1), array('id'));
        //保存做题记录
        if (!$checkR['id']) {
            $recordInsert = [
                'weid' => $weid,
                'uid' => $uid,
                'lessonid' => $lessonid,
                'sonid' => $sonid,
                'record' => serialize($rdata),
                'createtime' => time(),
                'updatetime' => time()
            ];
            pdo_insert('goouc_class_practice_record', $recordInsert);
        } else {
            //之前每次做题产生一条新的记录，这次改为，只有一条记录（为了这个原因），把原来的记录标记为删除状态
            $paramR = array('weid' => $weid, 'uid' => $uid, 'lessonid' => $lessonid, 'sonid' => $sonid, 'status' => 1, ':id' => $checkR['id']);
            $checkrelist = pdo_fetchall('select id from ' . tablename('goouc_class_practice_record') . ' where weid = :weid AND uid = :uid AND lessonid = :lessonid AND sonid = :sonid AND status = :status AND id <> :id', $paramR);
            if (!empty($checkrelist)) {
                foreach ($checkrelist as $k => $v) {
                    pdo_update('goouc_class_practice_record', array('status' => 2), array('id' => $v['id']));
                }
            }
            $recordUpdate = [
                'record' => serialize($rdata),
                'updatetime' => time()
            ];
            pdo_update('goouc_class_practice_record', $recordUpdate, array('id' => $checkR['id']));
        }
        //第一次做题统计星星(只统记录第一次获取星星的数量)
        $paramsFirst = array('weid' => $weid, 'uid' => $uid, 'sonid' => $sonid, 'lessonid' => $lessonid, 'status' => 1);
        $checkFirst = pdo_get('goouc_class_user_star', $paramsFirst, array('id', 'num'));
        if (!$checkFirst) {
            $starInsert = [
                'weid' => $weid,
                'uid' => $uid,
                'lessonid' => $lessonid,
                'sonid' => $sonid,
                'createtime' => time()
            ];
            $rightPercent = floor(($num / count($practiceList)) * 100) / 100;
            if ($rightPercent == 1) {
                $starNum = 3;
            } elseif (0.5 <= $rightPercent && $rightPercent < 1) {
                $starNum = 2;
            } elseif (0 < $rightPercent && $rightPercent < 0.5) {
                $starNum = 1;
            } elseif ($rightPercent == 0) {
                $starNum = 0;
            }
            $starInsert['num'] = $starNum;
            pdo_insert('goouc_class_user_star', $starInsert);
            $data['star'] = $starNum;
        } else {
            $data['star'] = $checkFirst['num'];
        }
        return $this->result(0, '闯关成功', $data);
    }

    /*
     * 做题解析接口
     *
     * */
    public function doPagePracticeRecordInfo()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $sonid = $_GPC['sonid'];
        $lessonid = $_GPC['lid'];
        $weid = $_W['uniacid'];
        $params = array(':weid' => $weid, ':uid' => $uid, ':lessonid' => $lessonid, ':sonid' => $sonid);
        $practiceRecord = pdo_fetchall("select * from " . tablename('goouc_class_practice_record') . "  where weid = :weid AND uid = :uid AND lessonid =:lessonid AND sonid=:sonid order by id desc limit 1", $params);
        $record = unserialize($practiceRecord[0]['record']);
        $types_config = array('1' => '判断题', '2' => '单选题', '3' => '多选题', '4' => '填空题');
        $weid = $_W['uniacid'];
        $paramsl = [':weid' => $weid, ':sonid' => $sonid, ':lessonid' => $lessonid, ':status' => 1];
        $practiceList = pdo_fetchall("select * from " . tablename('goouc_class_practice') . "  where weid = :weid AND sonid = :sonid AND status = :status AND lessonid = :lessonid", $paramsl);
        //var_dump($record);die;
        foreach ($practiceList as $k => &$v) {
            if ($v['thumb']) {
                $v['thumb'] = $this->getImgUrl($v['thumb']);
            }
            if ($v['type'] == 2 || $v['type'] == 3) {
                $v['items'] = unserialize($v['items']);
                if ($v['isimg'] == 1) {
                    $img_items = unserialize($v['img_items']);
                    foreach ($img_items as &$vi) {
                        $vi['p'] = $this->getImgUrl($vi['p']);
                    }
                    $v['img_items'] = $img_items;
                }
            } elseif ($v['type'] == 4) {
                //计算填空数
                $v['answersNum'] = explode("、", $v['answer']);//这个该怎么计算
            }
            $v['practiceType'] = $types_config[$v['type']];
            //用户该题对错
            $v['userstatus'] = $record[$v['id']]['status'];
            $v['useranswer'] = $record[$v['id']]['uanswer'];
        }
        return $this->result(0, '解析详情', $practiceList);
    }

    /*
     * 错题本首页接口
     *
     * 总的错题数
     * 取学科,课程id,课程标题
     * */
    public function doPagePracticeFalse()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $params = [':weid' => $weid, ':uid' => $uid, ':is_delete' => 1];
        $pList = pdo_fetchall("select fr.id,l.id as lid,su.name as subjectname,l.title from " . tablename('goouc_class_practice_false_record') . " fr LEFT JOIN " . tablename('goouc_class_lesson') . " l ON fr.lessonid = l.id LEFT JOIN " . tablename('goouc_class_subject') . " su ON l.subjectid = su.id" . "  where fr.weid = :weid AND fr.uid = :uid AND fr.is_delete = :is_delete ", $params);
        $practiceList = [];
        foreach ($pList as $k => $v) {
            $practiceList[$v['lid']] = [
                'subjectname' => $v['subjectname'],
                'title' => $v['title'],
                'lid' => $v['lid']
            ];
        }
        //统计学员总的错题数
        $tparams = array(':weid' => $weid, ':uid' => $uid, ':is_delete' => 1);
        $totalNum = pdo_fetchcolumn("select count(*) as total  from " . tablename('goouc_class_practice_false_record') . "  where weid = :weid AND uid = :uid AND is_delete = :is_delete", $tparams);
        $data = [
            'totalNum' => $totalNum,
            'list' => $practiceList
        ];
        return $this->result(0, '错题本数据', $data);
    }

    /*
     * 课程错题列表接口
     *
     * 用户答案
     * 取习题详情
     * */
    public function doPagePracticeFalseList()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        $lessonid = $_GPC['lid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        if (empty($lessonid)) {
            return $this->result(1, '课程id未获取到', array('code' => 3001, 'msg' => '课程id未获取到'));
        }
        $types_config = array('1' => '判断题', '2' => '单选题', '3' => '多选题', '4' => '填空题');
        $params = [':weid' => $weid, ':uid' => $uid, ':is_delete' => 1, ':lessonid' => $lessonid];
        $falseList = pdo_fetchall("select fr.useranswer,p.id,p.type,p.question,p.thumb,p.answer,p.items,p.img_items,p.analysis,p.isimg from " . tablename('goouc_class_practice_false_record') . " fr LEFT JOIN " . tablename('goouc_class_practice') . " p ON fr.practiceid = p.id " . " where fr.weid = :weid AND fr.uid = :uid AND fr.is_delete = :is_delete AND fr.lessonid = :lessonid", $params);
        foreach ($falseList as $k => &$v) {
            if ($v['thumb']) {
                $v['thumb'] = $this->getImgUrl($v['thumb']);
            }
            if ($v['type'] == 2 || $v['type'] == 3) {
                if ($v['items']) {
                    $v['items'] = unserialize($v['items']);
                }
                if ($v['isimg'] == 1) {
                    if ($v['img_items']) {
                        $img_items = unserialize($v['img_items']);
                        foreach ($img_items as &$vi) {
                            $vi['p'] = $this->getImgUrl($vi['p']);
                        }
                        $v['img_items'] = $img_items;
                    }
                }
            }
//            elseif ($v['type'] == 4) {
//                //计算填空数
//                $v['answersNum'] = explode("、", $v['answer']);//这个该怎么计算
//            }
        }
        return $this->result(0, '课程错题列表', $falseList);
    }

    /*
     * 删除错题接口
     * */
    public function doPagePracticeDel()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        $practiceid = $_GPC['practiceid'];
        $params = [':weid' => $weid, ':uid' => $uid, ':is_delete' => 1, ':practiceid' => $practiceid];
        $condition = ' weid = :weid AND uid = :uid AND is_delete = :is_delete AND practiceid = :practiceid ';
        $check = pdo_fetchcolumn("select id from " . tablename('goouc_class_practice_false_record') . "  where " . $condition, $params);
        if ($check) {
            $data['is_delete'] = 2;
            pdo_update('goouc_class_practice_false_record', $data, array('practiceid' => $practiceid, 'weid' => $weid, 'uid' => $uid));
            return $this->result(0, '删除成功');
        } else {
            return $this->result(0, '请刷新后重试');
        }
    }


    /*
     * 线下课程接口(用老页面)
     *
     * uid,weid,status=1,is_underline=1
     * */
    /*    public function doPagePracticeunderline()
        {
            global $_W, $_GPC;
            $uid = $_GPC['uid'];
            $weid = $_W['uniacid'];
            $phone = pdo_fetchcolumn("select phone from " . tablename('goouc_class_user') . "  where id = :uid", array(':uid' => $uid));
            $params = [':weid' => $weid, ':phone' => $phone, ':is_underline' => 1];
            $underlineList = pdo_fetchall("select l.* from " . tablename('goouc_class_lesson_underline_student') . " us LEFT JOIN " . tablename('goouc_class_lesson') . " l ON us.lesson_id = l.id " . " where us.weid = :weid AND us.phone = :phone AND l.is_underline = :is_underline", $params);

            //        foreach ($underlineList as $k => &$v) {
            //        //处理图片
            //        }
            return $this->result(0, '课程错题列表', $underlineList);
        }*/
    /*
     * 我的课程=>所有带习题的课程
     *
     * */
    public function doPagePracticeCenterLesson()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        //获取线上已报名的课程
        $contion = 's.weid = :weid AND s.uid = :uid';
        $params = [':weid' => $weid, ':uid' => $uid];
        $lessonList = [];
        $videoLesson = pdo_fetchall("select count(p.id) as pnum, s.id,s.uid,sj.name as subjectname,l.title as ltitle,l.id as lid,l.is_underline from " . tablename('goouc_class_user_signup') . " s LEFT JOIN " . tablename('goouc_class_lesson') . " l ON s.lessonid = l.id LEFT JOIN " . tablename('goouc_class_subject') . " sj ON l.subjectid = sj.id LEFT JOIN " . tablename('goouc_class_practice') . "p ON p.lessonid = l.id where " . $contion . " group by l.id", $params);
        //把存在习题的课程放在一个数组里
        $practiceLesson = [];
        foreach ($videoLesson as $kv => $vv) {
            if ($vv['pnum'] > 0) {
                $practiceLesson[] = $vv;
            }
        }
        //取线下课程
        $phone = pdo_fetchcolumn("select phone from " . tablename('goouc_class_user') . "  where id = :uid", array(':uid' => $uid));
        $uparams = [':weid' => $weid, ':phone' => $phone, ':is_underline' => 1];
        $underlineList = pdo_fetchall("select count(p.id) as pnum,sj.name as subjectname,l.title as ltitle,l.id as lid ,l.is_underline from " . tablename('goouc_class_lesson_underline_student') . " us LEFT JOIN " . tablename('goouc_class_lesson') . " l ON us.lesson_id = l.id LEFT JOIN " . tablename('goouc_class_subject') . " sj ON l.subjectid = sj.id LEFT JOIN " . tablename('goouc_class_practice') . "p ON p.lessonid = l.id  where us.weid = :weid AND us.phone = :phone AND l.is_underline = :is_underline group by l.id", $uparams);
        foreach ($underlineList as $ks => $vs) {
            if ($vs['pnum'] > 0) {
                $practiceLesson[] = $vs;
            }
        }
        foreach ($practiceLesson as &$v) {
            //章节总数量
            $tsql = "SELECT COUNT(*) FROM " . tablename('goouc_class_son') . " WHERE weid = :weid AND lessonid = :lessonid AND status = :status";
            $chaptertotal = pdo_fetchcolumn($tsql, array(':weid' => $weid, ':lessonid' => $v['lid'], ':status' => 1));
            //课程总星星数量
            $v['totalStar'] = 3 * $chaptertotal;
            //会员该课程获取到的星星数量
            $userstar = pdo_fetch("select sum(num) as totalnum from " . tablename('goouc_class_user_star') . " WHERE weid = :weid AND lessonid = :lessonid AND uid = :uid AND status = :status", array(':weid' => $weid, ':uid' => $uid, ':lessonid' => $v['lid'], ':status' => 1));
            $v['user_star'] = empty($userstar['totalnum']) ? 0 : $userstar['totalnum'];
            //学习进度条
            $studySon = pdo_fetchcolumn("select COUNT(*) as studySon FROM " . tablename('goouc_class_stady') . " cs LEFT JOIN " . tablename('goouc_class_son') . " s ON cs.sonid = s.id LEFT JOIN " . tablename('goouc_class_lesson') . " l ON s.lessonid = l.id where cs.weid = :weid AND cs.uid = :uid AND l.id = :lid AND s.status = :status", array(':weid' => $weid, ':uid' => $uid, ':lid' => $v['lid'], ':status' => 1));
            $v['jindu'] = $studySon / $chaptertotal;
            //最近一场直播时间
            //$nearvideo = pdo_fetch("select starttime from " . tablename('goouc_class_son') . " WHERE weid = :weid AND lessonid = :lessonid AND status = :status AND sontype <> :sontype AND starttime > :starttime AND starttime <= :endtime ORDER BY starttime asc limit 1", array(':weid' => $weid, ':lessonid' => $v['lid'], ':sontype' => 2, ':status' => 1, ':starttime' => strtotime(date('Y-m-d 00:00:00', time())), ':endtime' => strtotime(date('Y-m-d 23:59:59', time()))));
            //$v['video'] = empty($nearvideo['starttime']) ? 0 : date('H:s', $nearvideo['starttime']);//当天的直播章节时间
            //该课程学习状态
            $studyStatus = pdo_fetch("select id FROM " . tablename('goouc_class_user_study_speed') . " WHERE weid = :weid AND lessonid = :lessonid AND uid = :uid limit 1", array(':weid' => $weid, ':lessonid' => $v['lid'], ':uid' => $uid));
            $v['studyStatus'] = empty($studyStatus['id']) ? 2 : 1;//1:已学习 2:未学习
        }
        return $this->result(0, '课程错题列表', $practiceLesson);
    }

    /*
     * 个人中心页面：总共星星数量(暂时没用)
     *
     * */
    public function doPagePracticeTotalStar()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        $params = array(':weid' => $weid, ':uid' => $uid, ':status' => 1);
        $totalStar = pdo_fetchcolumn("select sum(num) as totalStar  from " . tablename('goouc_class_user_star') . "  where weid = :weid AND uid = :uid AND status = :status", $params);
        $totalStar = empty($totalStar) ? 0 : $totalStar;
        return $this->result(0, '星星总量', $totalStar);
    }

    /*
     *判断是不是内部学员(之前写的有逻辑，这个借口暂时没有用)
     *
     * */
    public function doPagePracticeUserStatus()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        $lessonid = $_GPC['lessonid'];
        if (empty($lessonid)) {
            return $this->result(1, '课程id未获取到', array('code' => 3001, 'msg' => '课程id未获取到'));
        }
        $phone = pdo_fetchcolumn("select phone from " . tablename('goouc_class_user') . "  where id = :uid", array(':uid' => $uid));
        $params = [':weid' => $weid, ':phone' => $phone, ':is_underline' => 1, ':lesson_id' => $lessonid];
        $check = pdo_fetchcolumn("select us.id from " . tablename('goouc_class_lesson_underline_student') . " us LEFT JOIN " . tablename('goouc_class_lesson') . " l ON us.lesson_id = l.id where us.weid = :weid AND us.phone = :phone AND l.is_underline = :is_underline AND us.lesson_id = :lesson_id", $params);
        $nbStatus = empty($check) ? 0 : 1;
        return $this->result(0, '线下课程，请联系管理员', $nbStatus);
    }

    /*
     *星际排行
     *
     * */
    public function doPagePracticeStarOrder()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        $type = empty($_GPC['type']) ? 1 : $_GPC['type'];//1：周  2：总
        if ($type == 1) {
            $beginWeek = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
            $endWeek = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"));
            $tparams = array(':weid' => $weid, ':start' => $beginWeek, ':end' => $endWeek, ':status' => 1);
            $totalAll = pdo_fetchall("select sum(us.num) as totalStar,us.uid,u.headimg,u.nickname,u.myheaderimg from " . tablename('goouc_class_user_star') . " us LEFT JOIN " . tablename('goouc_class_user') . " u ON us.uid = u.id  where us.weid = :weid AND us.status = :status AND us.createtime >= :start AND us.createtime <= :end  group by us.uid order by totalStar desc limit 0,23", $tparams);
            $params = array(':weid' => $weid, ':uid' => $uid, ':start' => $beginWeek, ':end' => $endWeek, ':status' => 1);
            $totalStar = pdo_fetchall("select sum(us.num) as totalStar,us.uid,u.nickname,u.headimg,u.myheaderimg from " . tablename('goouc_class_user_star') . " us LEFT JOIN " . tablename('goouc_class_user') . " u ON us.uid = u.id  where us.weid = :weid AND us.status = :status AND us.uid = :uid AND us.createtime >= :start AND us.createtime <= :end ", $params);
        } elseif ($type == 2) {
            $tparams = array(':weid' => $weid, ':status' => 1);
            $totalAll = pdo_fetchall("select sum(us.num) as totalStar,us.uid,u.headimg,u.nickname,u.myheaderimg from " . tablename('goouc_class_user_star') . " us LEFT JOIN " . tablename('goouc_class_user') . " u ON us.uid = u.id  where us.weid = :weid AND us.status = :status group by us.uid order by totalStar desc limit 0,23", $tparams);
            $params = array(':weid' => $weid, ':uid' => $uid, ':status' => 1);
            $totalStar = pdo_fetchall("select sum(us.num) as totalStar,us.uid,u.nickname,u.headimg,u.myheaderimg from " . tablename('goouc_class_user_star') . " us LEFT JOIN " . tablename('goouc_class_user') . " u ON us.uid = u.id  where us.weid = :weid AND us.uid = :uid AND us.status = :status ", $params);
        }
        //如果新用户没有数据要显示
        if (empty($totalStar[0]['uid'])) {
            $userInfo = pdo_get('goouc_class_user', array('id' => $uid), array('headimg', 'myheaderimg', 'nickname'));
            if (empty($userInfo['myheaderimg'])) {
                $totalStar[0]['headimg'] = $userInfo['headimg'];
            } else {
                $totalStar[0]['headimg'] = $userInfo['myheaderimg'];
            }
            $totalStar[0]['nickname'] = json_decode($userInfo['nickname']);
            $totalStar[0]['totalStar'] = 0;
            $totalStar[0]['uid'] = $uid;
        }else{
            $totalStar[0]['nickname'] = json_decode($totalStar[0]['nickname']);
        }
        $three = [];
        $lastList = [];
        foreach ($totalAll as $k => &$v) {
            if (empty($v['myheaderimg'])) {
                $v['headimg'] = $v['headimg'];
            } else {
                $v['headimg'] = $v['myheaderimg'];
            }
            $v['nickname'] = json_decode($v['nickname']);
            $idList[] = $v['uid'];
            $v['sort'] = $k + 1;
            if ($k < 3) {
                $three[] = $v;
                unset($totalAll[$k]);
            } else {
                $lastList[] = $v;
            }
        }
        //判断是否上榜
        if (is_array($idList)) {
            if (empty($totalStar[0]['myheaderimg'])) {
                $totalStar[0]['headimg'] = $totalStar[0]['headimg'];
            } else {
                $totalStar[0]['headimg'] = $totalStar[0]['myheaderimg'];
            }
            if (in_array($totalStar[0]['uid'], $idList)) {
                $totalStar[0]['status'] = 1;//上榜
                $totalStar[0]['sort'] = array_search($totalStar[0]['uid'], $idList) + 1;
            } else {
                $totalStar[0]['status'] = 2;//未上榜
            }
        }
        $data = [
            'three' => $three,//前三
            'list' => $lastList,//前20
            'totalStar' => $totalStar[0]//该会员总星星
        ];

        return $this->result(0, '星际排行', $data);
    }

    /*
     * 网站标题内容
     * */
    public function doPagePracticeWebSet()
    {
        $config = $this->module['config'];
        $info = [
            'webname' => $config['webname'],
            'iconname' => $config['iconname'],
            'icontitle' => $config['icontitle']
        ];
        return $this->result(0, '网站参数', $info);
    }

    //以下教师端接口
    /*
     *布置作业-->教师课程列表
     *
     * */
    public function doPageTeacherLesson()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $uInfo = pdo_get('goouc_class_user', array('id' => $uid, 'weid' => $weid), array('teacherid'));
        //取该老师名下的所有课程
        $params = [':weid' => $weid, ':teacherid' => $uInfo['teacherid'], ':status' => 1];
        $lessonlist = pdo_fetchall('select id,title,image,is_only,is_underline from ' . tablename($this->t_lesson) . " where weid = :weid AND teacherid = :teacherid AND status = :status", $params);
        foreach ($lessonlist as &$v) {
            //统计学习人数
            //$num = pdo_fetchcolumn('select count(*) as num from '.tablename('goouc_class_stady').' where weid = :weid and ')
            $v['image'] = $_W['attachurl'] . $v['image'];
            if ($v['is_underline'] == 1) {
                $num = pdo_fetchcolumn('select count(*) as num from ' . tablename('goouc_class_lesson_underline_student') . ' where weid = :weid and lesson_id = :lessonid', array(':weid' => $weid, ':lessonid' => $v['id']));
                $v['study_num'] = $num;
            } else {
                $num = pdo_fetchcolumn('select count(*) as num from ' . tablename('goouc_class_user_signup') . ' where weid = :weid and lessonid = :lessonid', array(':weid' => $weid, ':lessonid' => $v['id']));
                $v['study_num'] = $num;
            }
        }
        return $this->result(0, '教师课程列表', $lessonlist);
    }

    /*
     *布置作业-->课程的章节列表
     *
     * */
    public function doPageTeacherSon()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        $lid = $_GPC['lid'];
        $params = [':weid' => $weid, ':lessonid' => $lid, ':status' => 1];
        $sonlist = pdo_fetchall('select id,title from ' . tablename($this->t_son) . " where weid = :weid AND lessonid = :lessonid AND status = :status", $params);
        return $this->result(0, '章节列表', $sonlist);
    }

    /*
     *布置作业-->推送作业消息
     *
     * */
    public function doPageTeacherMessage()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        if (empty($uid)) {
            return $this->result(1, '用户id未获取到', array('code' => 3001, 'msg' => '用户id未获取到'));
        }
        $weid = $_W['uniacid'];
        $lid = $_GPC['lid'];
        $sonidlist = json_decode(htmlspecialchars_decode($_GPC['sonid']), true);//[12,44,53453,634]
        $endtime = $_GPC['endtime'];
        $title = $_GPC['title'];//任务名称
        $message = $_GPC['message'];//推送消息
        $params = [':weid' => $weid, ':lid' => $lid];
        //判断是线上课，还是线下课
        $checkLid = pdo_get('goouc_class_lesson', array('weid' => $weid, 'id' => $lid), array('is_underline', 'title'));
        if ($checkLid['is_underline'] == 1) {
            $phonelist = pdo_fetchall('select phone from ' . tablename('goouc_class_lesson_underline_student') . ' where weid = :weid AND lesson_id = :lid', array(':weid' => $weid, ':lid' => $lid));
            foreach ($phonelist as $k => $v) {
                $userid = pdo_fetchcolumn('select id from ' . tablename('goouc_class_user') . ' where phone = :phone and weid=:weid', array(':phone' => $v['phone'], ':weid' => $weid));
                if ($userid) {
                    $sidlist[] = $userid;
                }
            }
        } else {
            $studentlist = pdo_fetchall('select uid from ' . tablename('goouc_class_user_signup') . ' where weid = :weid AND lessonid = :lid', $params);
            //保存数据
            $sidlist = [];
            foreach ($studentlist as $v) {
                //获取用户的
                $sidlist[] = $v['uid'];
            }
        }
        if ($endtime < (time() + 1200)) {
            return $this->result(1, '请至少预留20分钟作业时间');
        }
        //保存数据
        $data = [
            'weid' => $weid,
            'uid' => $uid,
            'lessonid' => $lid,
            'sonid' => serialize($sonidlist),
            'studentid' => serialize($sidlist),
            'totalstudent' => count($sidlist),
            'totalson' => count($sonidlist),
            'endtime' => $endtime,
            'title' => $title,
            'message' => $message,
            'createtime' => time(),
            'datetime' => date('Y-m-d', time())
        ];
        $re = pdo_insert('goouc_class_teacher_task', $data);
        if ($re) {
            //推送消息
            $config = $this->module['config'];
            $kaiguan = $config['practice_remind'];
            $duanxin = $config['duanxin_status'];
            $template_id = $config['templateid'];
            $teachername = pdo_fetchcolumn('select t.name from ' . tablename('goouc_class_user') . ' u LEFT JOIN ' . tablename('goouc_class_teacher') . ' t on u.teacherid = t.id where u.weid=:weid and u.id = :uid ', array(':weid' => $weid, ':uid' => $uid));
            foreach ($sidlist as $k => $v) {
                //获取openid
                $studentinfo = pdo_get('goouc_class_user', array('weid' => $weid, 'id' => $v), array('openid', 'nickname', 'name', 'phone'));
                $studentinfo['nickname'] = json_decode($studentinfo['nickname']);
                if ($kaiguan) {
                    $messagedata = [
                        'thing5' => ['value' => $title],
                        'name2' => ['value' => $studentinfo['nickname']],
                        'thing9' => ['value' => $message],
                        'name11' => ['value' => $teachername],
                        'date4' => ['value' => date('Y-m-d H:i:s', $endtime)]
                    ];
                    $this->sendMessage($studentinfo['openid'], $messagedata, $template_id);
                }
                if ($duanxin == 1) {
                    $name = empty($studentinfo['name']) ? $studentinfo['nickname'] : $studentinfo['name'];
                    if (!empty($studentinfo['phone']) && preg_match('/^[1][3,4,5,7,8,9][0-9]{9}$/', $studentinfo['phone'])) {
                        $this->practiceSendMessage($studentinfo['phone'], 1, $name, $checkLid['title'], date('Y-m-d H:i:s', $endtime));
                    }
                }
            }
            return $this->result(0, '作业布置完成');
        } else {
            return $this->result(1, '作业布置失败');
        }
    }

    //推送订阅消息   请认真完成，已完成的忽略    这是本次的英语作业
    function sendMessage($openid = '', $data = [], $template_id = '')
    {
        global $_W;
        $appid = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $access_token = json_decode($this->curl_get($url), true)['access_token'];
        $post = [];
        $post['touser'] = $openid;
        $post['page'] = 'pages/home/home';//跳转到到课程页面
        $post['template_id'] = $template_id;
        $post['data'] = $data;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
        $re = $this->https_post($url, json_encode($post));
        return $re;
    }

    function https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }

    /*
     *学情查看-->所有的作业列表（根据课程统计）
     *
     * */
    public function doPageTeacherTask()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        $params = [':weid' => $weid, ':uid' => $uid];
        $datetime = $_GPC['keywords'];
        $pageindex = max(1, $_GPC['page']);
        $psize = 8;
        //有筛选
        $taskList = pdo_fetchall('select t.id, t.createtime,l.title,l.image,t.id as tid,l.id as lid,t.datetime from ' . tablename('goouc_class_teacher_task') . " t LEFT JOIN " . tablename('goouc_class_lesson') . " l ON t.lessonid = l.id where t.weid = :weid AND t.uid = :uid order by createtime desc LIMIT " . ($pageindex - 1) * $psize . ',' . $psize, $params);
        $getdate = pdo_fetchall('select t.datetime from ' . tablename('goouc_class_teacher_task') . " t LEFT JOIN " . tablename('goouc_class_lesson') . " l ON t.lessonid = l.id where t.weid = :weid AND t.uid = :uid ", $params);
        $total = count($getdate);
        foreach ($getdate as $v) {
            $date[] = $v['datetime'];
        }
        if (!empty($datetime)) {
            $params = [':weid' => $weid, ':uid' => $uid, ':datetime' => $datetime];
            $taskList = pdo_fetchall('select t.createtime,l.title,l.image,t.id as tid,l.id as lid,t.datetime from ' . tablename('goouc_class_teacher_task') . " t LEFT JOIN " . tablename('goouc_class_lesson') . " l ON t.lessonid = l.id where t.weid = :weid AND t.uid = :uid AND t.datetime = :datetime order by createtime desc LIMIT " . ($pageindex - 1) * $psize . ',' . $psize, $params);
            $total = pdo_fetchcolumn('select count(*) from ' . tablename('goouc_class_teacher_task') . " t LEFT JOIN " . tablename('goouc_class_lesson') . " l ON t.lessonid = l.id where t.weid = :weid AND t.uid = :uid  AND t.datetime = :datetime", $params);
        }
        foreach ($taskList as &$v) {
            $v['image'] = $_W['attachurl'] . $v['image'];
        }
        $page = ceil($total / $psize);
        return $this->result(0, '作业列表', ['data' => $taskList, 'pages' => $page, 'datetime' => $date]);
    }

    /*
     *学情查看-->作业完成情况（该次作业每个课程的）
     *
     * */
    public function doPageTeacherTaskInfo()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $taskid = $_GPC['taskid'];
        $weid = $_W['uniacid'];
        $taskInfo = pdo_get('goouc_class_teacher_task', array('id' => $taskid, 'weid' => $weid));
        //总共布置给了多少人
        $studentlist = unserialize($taskInfo['studentid']);
        $sonlist = unserialize($taskInfo['sonid']);
        $sonStr = implode($sonlist, ',');
        //遍历统计谁全部做了，谁没做完
        $unfinish = [];
        $finish = [];
        $unfinishnum = 0;
        $finishnum = 0;
        foreach ($studentlist as $k => $v) {
            $params = [':weid' => $weid, ':uid' => $v, ':lessonid' => $taskInfo['lessonid']];
            $count = pdo_fetchcolumn('select count(*) as num from ' . tablename('goouc_class_practice_record') . ' where weid = :weid AND uid = :uid AND lessonid = :lessonid AND sonid in (' . $sonStr . ')', $params);
            $name = pdo_fetchcolumn('select nickname from ' . tablename('goouc_class_user') . ' where weid = :weid AND id = :id', array(':weid' => $weid, ':id' => $v));
            if ($count < $taskInfo['totalson']) {
                $unfinish[$k]['id'] = $v;
                $unfinish[$k]['name'] = json_decode($name);
                $unfinishnum++;
            } else {
                $finish[$k]['id'] = $v;
                $finish[$k]['name'] = json_decode($name);
                $finishnum++;
            }
        }
        //完成率
        if ($taskInfo['totalstudent'] == 0) {
            $percent = 0;
        } else {
            $percent = floor(($finishnum / $taskInfo['totalstudent']) * 100);
        }
        return $this->result(0, '作业完成情况', ['percent' => $percent, 'finish' => ['finishnum' => $finishnum, 'data' => $finish], 'unfinish' => ['unfinishnum' => $unfinishnum, 'data' => $unfinish]]);
    }

    /*
     *学情查看-->试题完成情况（该次作业每个课程的）
     *
     * */
    public function doPageTeacherTaskPractice()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        $taskid = $_GPC['taskid'];
        $taskInfo = pdo_get('goouc_class_teacher_task', array('id' => $taskid, 'weid' => $weid));
        //总共布置给了多少人
        $studentlist = unserialize($taskInfo['studentid']);
        $sonlist = unserialize($taskInfo['sonid']);
        $studentStr = implode($studentlist, ',');
        //遍历统计谁全部做了，谁没做完
        $data = [];
        foreach ($sonlist as $k => $v) {
            $params = [':weid' => $weid, ':sonid' => $v];
            $count = pdo_fetchcolumn('select count(*) as num from ' . tablename('goouc_class_practice_record') . ' where weid = :weid AND sonid = :sonid AND uid in (' . $studentStr . ')', $params);
            $percent = ($count < 0) ? 0 : (floor(($count / $taskInfo['totalstudent']) * 100));
            $title = pdo_fetchcolumn('select title from ' . tablename('goouc_class_son') . ' where weid = :weid AND id = :id', array(':weid' => $weid, ':id' => $v));
            $data[$k]['sonid'] = $v;
            $data[$k]['taskid'] = $taskid;
            $data[$k]['percent'] = $percent;
            $data[$k]['title'] = $title;
        }
        return $this->result(0, '试题完成情况', $data);
    }

    /*
     *学情查看-->错题单个汇总（该次作业每个课程的）
     *
     * */
    public function doPageTeacherTaskAnalysis()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $weid = $_W['uniacid'];
        $taskid = $_GPC['taskid'];
        $sonid = $_GPC['sonid'];
        $taskInfo = pdo_get('goouc_class_teacher_task', array('id' => $taskid, 'weid' => $weid), array('studentid'));
        $studentlist = unserialize($taskInfo['studentid']);
        $studentStr = implode($studentlist, ',');
        $params = [':weid' => $weid, ':sonid' => $sonid, ':status' => 1];
        $list = pdo_fetchall('select * from ' . tablename('goouc_class_practice_record') . ' where weid = :weid AND sonid = :sonid AND status =:status AND uid in (' . $studentStr . ') order by id desc ', $params);
        $truelist = [];
        foreach ($list as $key => $val) {
            $record = unserialize($val['record']);
            foreach ($record as $k => $v) {
                if ($v['status'] == 1) {
                    $truelist[$k]['trueid'][] = $val['uid'];
                } elseif ($v['status'] == 0) {
                    $truelist[$k]['falseid'][] = $val['uid'];
                }
            }
        }
        unset($v);
        unset($val);
        //统计每题正确率
        $practicelist = [];
        foreach ($truelist as $tk => $tv) {
            $practicelist[$tk]['id'] = $tk;
            if (is_array($tv['trueid'])) {
                $practicelist[$tk]['percent'] = floor((count($tv['trueid']) / count($list)) * 100);
                foreach ($tv['trueid'] as $sk => $sv) {
                    $name = pdo_fetchcolumn('select nickname from ' . tablename('goouc_class_user') . ' where id=:id AND weid = :weid', array(':id' => $sv, ':weid' => $weid));
                    $practicelist[$tk]['truedata'][] = json_decode($name);
                }
            } else {
                $practicelist[$tk]['percent'] = 0;
            }
//            if (is_array($tv['trueid'])) {
//                foreach ($tv['trueid'] as $sk => $sv) {
//                    $name = pdo_fetchcolumn('select nickname from ' . tablename('goouc_class_user') . ' where id=:id AND weid = :weid', array(':id' => $sv, ':weid' => $weid));
//                    $practicelist[$tk]['truedata'][] = json_decode($name);
//                }
//                unset($sv);
//            }
            if (is_array($tv['falseid'])) {
                foreach ($tv['falseid'] as $fk => $fv) {
                    $fname = pdo_fetchcolumn('select nickname from ' . tablename('goouc_class_user') . ' where id=:id AND weid = :weid', array(':id' => $fv, ':weid' => $weid));
                    $practicelist[$tk]['falsedata'][] = json_decode($fname);
                }
            }
            if (!isset($practicelist[$tk]['falsedata'])) {
                $practicelist[$tk]['falsedata'] = [];
            }
            if (!isset($practicelist[$tk]['truedata'])) {
                $practicelist[$tk]['truedata'] = [];
            }
        }
        $lastlist = [];
        foreach ($practicelist as $k => $v) {
            $lastlist[] = $v;
        }
        unset($v);
        //$percent = array_column($practicelist, 'percent');
        //array_multisort($percent, SORT_DESC, $practicelist);
        return $this->result(0, '试题完成情况', $lastlist);
    }

    /*
     * 单个习题详情
     *
     * */
    public function doPageTeacherpracticeInfo()
    {
        global $_W, $_GPC;
        $weid = $_W['uniacid'];
        $practiceid = $_GPC['practiceid'];
        $info = pdo_get('goouc_class_practice', array('weid' => $weid, 'id' => $practiceid), array('type', 'question', 'thumb', 'answer', 'items', 'img_items', 'analysis', 'isimg'));
        if ($info['thumb']) {
            $info['thumb'] = $_W['attachurl'] . $info['thumb'];
        }
        if ($info['type'] == 2 || $info['type'] == 3) {
            $info['items'] = unserialize($info['items']);
            if ($info['isimg'] == 1) {
                $img_items = unserialize($info['img_items']);
                foreach ($img_items as &$vi) {
                    $vi['p'] = $_W['attachurl'] . $vi['p'];
                }
                $info['img_items'] = $img_items;
            }
        } elseif ($info['type'] == 4) {
            //计算填空数
            $info['answersNum'] = explode("、", $info['answer']);//这个该怎么计算
        }
        $types_config = array('1' => '判断题', '2' => '单选题', '3' => '多选题', '4' => '填空题');
        $info['practiceType'] = $types_config[$info['type']];
        return $this->result(0, '单个试题详情', $info);
    }

    /*
     * 催促
     * */
    public function doPageTeacherRemind()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $taskid = $_GPC['taskid'];
        $weid = $_W['uniacid'];
        $taskInfo = pdo_get('goouc_class_teacher_task', array('id' => $taskid, 'weid' => $weid));
        //总共布置给了多少人
        $studentlist = unserialize($taskInfo['studentid']);
        $sonlist = unserialize($taskInfo['sonid']);
        $sonStr = implode($sonlist, ',');
        //遍历统计谁全部做了，谁没做完
        $config = $this->module['config'];
        $template_id = $config['ntemplateid'];
        $kaiguan = $config['practice_remind'];
        $duanxin = $config['duanxin_status'];
        $lessontitle = pdo_get('goouc_class_lesson', array('id' => $taskInfo['lessonid']), array('title'));
        if ($studentlist) {
            foreach ($studentlist as $k => $v) {
                $params = [':weid' => $weid, ':uid' => $v, ':lessonid' => $taskInfo['lessonid']];
                $count = pdo_fetchcolumn('select count(*) as num from ' . tablename('goouc_class_practice_record') . ' where weid = :weid AND uid = :uid AND lessonid = :lessonid AND sonid in (' . $sonStr . ')', $params);
                if ($count < $taskInfo['totalson']) {
                    $uinfo = pdo_get('goouc_class_user', array('weid' => $weid, 'id' => $v), array('nickname', 'name', 'openid', 'phone'));
                    if ($kaiguan == 1) {
                        $messagedata = [
                            'name2' => ['value' => json_decode($uinfo['nickname'])],
                            'thing3' => ['value' => $taskInfo['title']],
                            'thing4' => ['value' => '作业未完成'],
                        ];
                        $this->sendMessage($uinfo['openid'], $messagedata, $template_id);
                    }
                    if ($duanxin == 1) {
                        $name = empty(json_decode($uinfo['name'])) ? json_decode($uinfo['nickname']) : json_decode($uinfo['name']);
                        if (!empty($uinfo['phone']) && preg_match('/^[1][3,4,5,7,8,9][0-9]{9}$/', $uinfo['phone'])) {
                            $this->practiceSendMessage($uinfo['phone'], 2, $name, $lessontitle['title']);
                        }
                    }
                }
            }
        }
        return $this->result(0, '提醒成功!');
    }

    function practiceSendMessage($phone, $type, $name, $title = '', $end = '')
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        if ($type == 1) {
            $TemplateCode = $config['TemplateCode1'];
            $message = [
                'type' => 1,
                'name' => $name,
                "title" => $title,
                'time' => $end,
            ];
        } else {
            $TemplateCode = $config['TemplateCode2'];
            $message = [
                'type' => 2,
                'name' => $name,
                "title" => $title,
            ];
        }
        $phoneset = array('accessKeyId' => $config['accessKeyId'], 'accessKeySecret' => $config['accessKeySecret'], 'SignName' => $config['SignName'], 'TemplateCode' => $TemplateCode);
        $obj = new send();
        $res = $obj->sendcode($phone, $message, $phoneset);
        $res = json_decode(json_encode($res), true);
        if ($res['Code'] != 'OK') {
            return $this->result(0, '发送失败', 1);
        }
    }

    //小程序手机号注册登录
    public function doPageSmallLogin()
    {
        global $_W, $_GPC;
        $phone = $_GPC['phone'];
        $smsCode = $_GPC['smscode'];
        $tuid = $_GPC['tuid'];//推荐人uid
        $weid = $_W['uniacid'];
        $config = $this->module['config'];
        if (!$phone || !$smsCode) {
            return $this->result(0, '手机号或验证码为空', ['code' => 1003, 'msg' => '手机号或验证码为空']);
        }
        //验证手机号
        if ((strlen($phone) != 11) || !$this->is_Mobile($phone)) {
            return $this->result(0, '手机号格式错误', ['code' => 1003, 'msg' => '手机号格式错误']);
        }
        //验证验证码
        $checkCode = pdo_fetch('select * from ' . tablename('goouc_class_phonecode') . ' where weid = :weid AND phone = :phone order by id desc', array(':weid' => $weid, ':phone' => $phone));
        if (($checkCode['createtime'] + 300) < time()) {
            return $this->result(0, '验证码已过期', ['code' => 1003, 'msg' => '验证码已过期']);
        }
        if ($checkCode['code'] != $smsCode) {
            return $this->result(0, '验证码错误', ['code' => 1003, 'msg' => '验证码错误']);
        }
        //验证成功
        $checkM = pdo_get('goouc_class_user', array('phone' => $phone, 'weid' => $weid), array('id', 'status'));
        if (!$checkM) {
            $data = [
                'weid' => $weid,
                'phone' => $phone,
                'createtime' => time(),
                'loginstatus' => 1
            ];
            $res = pdo_insert($this->t_user, $data);
            if ($res) {
                $uid = pdo_insertid();
                //注册成功，返兑换币
                if ($config['nstatus'] == 1) {
                    pdo_update($this->t_user, array('card' => $config['nnum']), array('id' => $uid));
                }
                //分享奖励是否开启（开启存值发奖励）
                $shar = array('weid' => $weid, 'uid' => $tuid, 'buid' => $uid, 'date' => date('Ymd'));
                pdo_insert('goouc_class_usershar', $shar);
                if ($config['sstatus'] == 1) {
                    //判断分享次数
                    $from_user_num = pdo_fetchcolumn("select count(*) from " . tablename('goouc_class_usershar') . " where weid=:weid AND uid=:uid AND date=:date AND buid != 0", array(':weid' => $weid, ':uid' => $tuid, ':date' => date('Ymd')));
                    //判断分享者今天分享的总共得到多少张
                    if ($from_user_num * $config['snum'] <= $config['zsnum']) {
                        //给分享者添加
                        pdo_query('update  ' . tablename('goouc_class_user') . ' set card = card +' . $config['snum'] . ' where weid=:weid AND id=:id', array(':weid' => $weid, ':id' => $tuid));
                    }
                }
                //给用户生成token验证值
                $token = $this->createtoken();
                $dat = [
                    'weid' => $_W['uniacid'],
                    'uid' => $uid,
                    'token' => $token,
                    'createtime' => time()
                ];
                //插入user_token数据表
                $ress = pdo_insert($this->t_user_token, $dat);
                if (!$ress) {
                    return $this->result(0, '生成token失败了,请重新登录', ['code' => 4001, 'uid' => $uid]);
                }
                return $this->result(0, '返回用户id以及token', ['uid' => $uid, 'code' => 200, 'token' => $token]);
            } else {
                return $this->result(0, '看数据', ['msg' => '新用户注册失败', 'code' => 1003]);
            }
        } else {
            if ($checkM['status'] == 0) {
                return $this->getresult(0, '账户被禁用，暂时不可登录小程序', ['msg' => '账户被禁用，暂时不可登录小程序', 'code' => 1003]);
            } else {
                //给用户生成token验证值
                $token = $this->createtoken();
                //插入user_token数据表
                $has_token = pdo_get($this->t_user_token, ['weid' => $_W['uniacid'], 'uid' => $checkM['id']], array('id'));
                if ($has_token) {
                    $ress = pdo_update($this->t_user_token, array('token' => $token, 'createtime' => time()), array('id' => $has_token['id']));
                } else {
                    //插入user_token数据表
                    $dat = [
                        'weid' => $_W['uniacid'],
                        'uid' => $checkM['id'],
                        'token' => $token,
                        'createtime' => time()
                    ];
                    $ress = pdo_insert($this->t_user_token, $dat);
                }
                if (!$ress) {
                    return $this->getresult(0, '生成token失败了,请重新登录', ['code' => 4001, 'uid' => $checkM['id']]);
                }
                return $this->getresult(0, '登陆成功', ['code' => 200, 'uid' => $checkM['id'], 'token' => $token]);
            }
        }
    }

    /**
     * 绑定微信
     */
    public function doPageSmallBindwx()
    {
        global $_W, $_GPC;
        $uid = $_GPC['uid'];
        $code = trim($_GPC['code']);
        $iv = $_GPC['iv'];
        $encryptedData = $_GPC['encryptedData'];
        $appid = $_W['account']['key'];
        $weid = $_W['uniacid'];
        //检测用户是否绑定了微信
        $checkB = pdo_get('goouc_class_user', array('id' => $uid, 'weid' => $weid), array('openid', 'status'));
        if ($checkB['status'] == 2) {
            return $this->result(1, '该用户被禁用，暂时无法登陆小程序', ['code' => 1001, 'msg' => '该用户被禁用，暂时无法登陆小程序']);
        }
        if (empty($checkB['openid'])) {
            return $this->result(1, '已绑定', ['code' => 1001, 'msg' => '已绑定']);
        }
        if (!empty($code) && !empty($iv) && !empty($encryptedData)) {
            $info = json_decode($this->getopenidnew($code), true);
            $session_key = $info['session_key'];
            $pc = new WXBizDataCrypt($appid, $session_key);
            $pc->decryptData($encryptedData, $iv, $dat);
            $info = json_decode($dat, true);
            if (empty($info)) {
                return $this->result(1, '解密获取用户信息失败', ['code' => 1001, 'msg' => '解密获取用户信息失败']);
            }
            $userinfo = pdo_fetch("SELECT `id`,`status`,`unionId` FROM " . tablename($this->t_user) . " WHERE openid = :openid AND weid = :weid", array(':openid' => $info['openId'], ':weid' => $_W['uniacid']));
            //先产寻openid是否存在  不存在的话 再查一下unionId对应的用户是否存在
            if (empty($userinfo)) {
                $data = array();
                $data['openid'] = $info['openId'];
                $data['nickname'] = $info['nickName'];
                $data['headimg'] = $info['avatarUrl'];
                if (empty($data['nickname']) || empty($data['openid'])) {
                    return $this->result(1, '用户注册失败', ['code' => 1003, 'msg' => '用户注册失败']);
                }
                $res = pdo_update($this->t_user, $data, array('weid' => $weid, 'id' => $uid));
                if ($res) {
                    return $this->result(0, '绑定成功', array('uid' => $uid));
                } else {
                    return $this->result(1, '用户注册失败', ['code' => 1003, 'msg' => '用户注册失败']);
                }
            } else {
                return $this->result(0, '该微信已经绑定了别的账户', ['code' => 1003, 'msg' => '该微信已经绑定了别的账户']);
            }
        } else {
            return $this->result(1, '未获取到code等参数值', ['code' => 1002, 'msg' => '未获取到code等参数值']);
        }
    }

    /**
     * 极光聊天室初始化
     */
    public function doPageInitJM()
    {
        global $_W, $_GPC;
        $config = $this->module['config'];
        $appkey = $config['jmkey'];
        $appsecret = $config['jmsecret'];
        //毫秒时间戳
        list($msec, $sec) = explode(' ', microtime());
        $timestamp = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $random_str = $this->getRandomStr(32);
        $signature = md5("appkey=" . $appkey . "&timestamp=" . $timestamp . "&random_str=" . $random_str . "&key=" . $appsecret);
        return $this->result(0, '极光初始化参数', ['code' => 200, 'appkey' => $appkey, 'random_str' => $random_str, 'signature' => $signature, 'timestamp' => $timestamp, 'appsecret' => $appsecret]);
    }

    //获取随机字符串
    function getRandomStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    //新版推荐课程
    public function doPageRecom(){
        global $_W, $_GPC;
        $weid = $_W['uniacid'];
        $contion = "l.weid = :weid AND l.status = 1";
        $params[':weid'] = $weid;
        $contion .= '  AND  l.voidtypeid != 0 AND l.teacherid != 0 AND l.subjectid != 0 AND l.cityid != 0';
        $lesson = pdo_fetchall("SELECT l.id,`title`,`image`,`paytype`,`xhbnumber`,`pay_money`,`old_money`,`is_only`,`is_groupbuy`,`fic_study_num`,`study_num`,`pay_num` FROM " . tablename($this->t_lesson) . " l JOIN " . tablename($this->t_teacher) . " t ON l.teacherid = t.id WHERE " . $contion . " and recommend  = 1 ORDER BY  rand() limit 4 ", $params);
        return $this->result(0, '极光初始化参数', ['code' => 200, 'lesson' => $lesson]);
    }
}